B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Private p_cliente As Panel
	Dim cuest As C_Cuestionario
	Dim g As GPS
	Dim ruta As String
	Dim skmt As SQL
	Dim clie_id As String
	Dim sDate,sTime As String
	Dim usuario As String
	Dim total_cliente As String
	Dim m_lat, m_lon As String
	Dim btAdmin As BluetoothAdmin
	Dim cmp20 As Serial
	Dim printer As TextWriter
	Dim PairedDevices As Map
	Dim L As List
	Dim TAMANO As Int
	Dim ESPACIO As Int
	Dim BLANCO As String
	Dim cuenta As String
	Dim tipo_venta As String
	Dim MAC_IMPRESORA As String
	Dim btAdmin As BluetoothAdmin
	Dim Printer1 As EscPosPrinter
	Private location2 As Location
	Dim c As Cursor
	Dim s As Cursor
	Dim DD As Cursor
	Dim c2 As Cursor
	Dim ListView1 As ListView
	Dim la_cuenta As Label
	Dim La_nombre As Label
	Dim la_Calle As Label
	Dim la_numero As Label
	Dim la_nint As Label
	Dim la_edo As Label
	Dim la_pob As Label
	Dim la_col As Label
	Dim la_cp As Label
	Dim la_zona As Label
	Dim gest As Button
	Dim la_saldotot As Label
	Dim la_saldooper As Label
	Private l_cajetillas As Label
	Dim Tels As Button
	Dim Label10 As Label
	Dim Label11 As Label
	
	Dim Tar As Button
	Dim t1, t2 As Timer
	Dim la_comm As Label
	Dim la_actdte As Label
	Dim la_usuario As Label
	Dim la_resultado As Label
	Dim l_entre1 As Label
	Dim l_entre2 As Label
	Dim l_atiende As Label
	Dim l_atiende2 As Label
	Dim DATOS As Button
	Dim Guardar As Button
	Dim NUEVO As Button
	'    Dim lat_gps, lon_gps As String

	Dim l_total As Label
	Dim c2 As Cursor
	Dim S2 As Cursor
	Private s As Cursor
	Dim res As String
	Private HIST As Button
	Private MONTO_COMPRA As String
	Private META As String
	Private META2 As String
	Private VERIFICA As String
	Private L_QR As Label
	Private BT_QR As Button
	'Private qr As QRCode
	Dim CODIGO As String

	Private b_mapa As Button
	Dim CUANTOS As String
	Private B_IMP As Button
	Dim Toggla As Toggle
	Dim tgl As Toggle
	Private Panel1 As Panel
	Private I_COMPRA As EditText
	Private B_GUARDA_C As Button
	Private b_venta As Button
	Dim ALMACEN As String
	Dim LA_GPS As Label
	Private B_E_NEXT As Button
	Private E_RES_E As EditText
	Private t_tenc As Label
	Private Panel2 As Panel
	Private CONTADOR_E As String
	Private HR_RES1 As String
	Private HR_RES2 As String
	Private HR_RES3 As String
	Private EXISTE As String
	Private telefono As String
	
	
	Private RB1 As RadioButton
	Private RB2 As RadioButton
	Private RB3 As RadioButton
	Private RB4 As RadioButton
	Private RB5 As RadioButton
	
	Private stay_hh As String
	Private stay_mi As String
	Private stay_ss As String
	
	Private LA_GEO As Label
	Dim result As Int
	Private cercavalor As String
	Private LA_RUTA As String
	
	Private b_like As Button
	Private B_GPS As Button
	Dim sc As JhsIceZxing1
	Dim CODIGO As String
	Private SV_ENCUESTA As ScrollView
	Private RB1_E1 As RadioButton
	Private RB2_E1 As RadioButton
	Private RB3_E1 As RadioButton
	Private CHB1 As CheckBox
	Private CHB2 As CheckBox
	Private CHB3 As CheckBox
	Private Panel5 As Panel
	Private B_guardaencuesta As Button
	Private RadioButton1 As RadioButton
	Private RadioButton2 As RadioButton
	Private RadioButton3 As RadioButton
	Private RadioButton4 As RadioButton
	Private RadioButton5 As RadioButton
	Private RadioButton6 As RadioButton
	Private RadioButton7 As RadioButton
	Private RadioButton8 As RadioButton
	Private RadioButton9 As RadioButton
	Private RadioButton10 As RadioButton
	Private RadioButton11 As RadioButton
	Private RadioButton12 As RadioButton
	Private RadioButton13 As RadioButton
	Private RadioButton14 As RadioButton
	Private CheckBox1 As CheckBox
	Private CheckBox2 As CheckBox
	Private CheckBox3 As CheckBox
	Private CheckBox4 As CheckBox
	Private CheckBox5 As CheckBox
	Private CheckBox6 As CheckBox
	Private CheckBox7 As CheckBox
	Private CheckBox8 As CheckBox
	Dim encuentasmapa As Map
	Private p6 As EditText
	Private p7 As EditText
	Private p8 As EditText
	Private Panel7 As Panel
	Private RadioButton17 As RadioButton
	Private RadioButton16 As RadioButton
	Private RadioButton15 As RadioButton
	Private B_guardaencuesta_m2 As Button
	Private et_p1_m2 As EditText
	Private et_p2_m2 As EditText
	Private RB7_P6_M2 As RadioButton
	Private RB6_P6_M2 As RadioButton
	Private RB5_P6_M2 As RadioButton
	Private RB4_P6_M2 As RadioButton
	Private RB3_P6_M2 As RadioButton
	Private RB2_P6_M2 As RadioButton
	Private RB1_P6_M2 As RadioButton
	Private et_p5_m2 As EditText
	Private rd3_p4_m2 As RadioButton
	Private rd2_p4_m2 As RadioButton
	Private rd1_p4_m2 As RadioButton
	Private RB1_P3_M2 As RadioButton
	Private RB2_P3_M2 As RadioButton
	Private RB3_P3_M2 As RadioButton
	Private RB4_P3_M2 As RadioButton
	Private ET_P3_M2 As EditText
	Private Panel7_M2 As Panel
	Private P4_M2 As String
	Private P3_M2 As String
	Private P6_M2 As String
	
	Private CB1_P3_M2 As CheckBox
	Private CB2_P3_M2 As CheckBox
	Private CB3_P3_M2 As CheckBox
	Private CB4_P3_M2 As CheckBox
	Private CB5_P3_M2 As CheckBox
	Private CB6_P3_M2 As CheckBox
	Private EXISTE2 As String
	Private EXISTE3 As String
	Private EXISTE4 As String
	Private EXISTE5 As String
	Private et_p1_m3 As EditText
	Private et_p2_m3 As EditText
	Private CB1_P3_M3 As CheckBox
	Private CB2_P3_M3 As CheckBox
	Private CB3_P3_M3 As CheckBox
	Private CB4_P3_M3 As CheckBox
	Private CB5_P3_M3 As CheckBox
	Private CB1_P4_M3 As CheckBox
	Private CB2_P4_M3 As CheckBox
	Private CB3_P4_M3 As CheckBox
	Private CB4_P4_M3 As CheckBox
	Private CB5_P4_M3 As CheckBox
	Private rd1_p5_m3 As RadioButton
	Private rd2_p5_m3 As RadioButton
	Private CB1_P6_M3 As CheckBox
	Private CB2_P6_M3 As CheckBox
	Private CB3_P6_M3 As CheckBox
	Private CB4_P6_M3 As CheckBox
	Private CB5_P6_M3 As CheckBox
	Private CB6_P6_M3 As CheckBox
	Private ET_P6_M3 As EditText
	Private CB1_P7_M3 As CheckBox
	Private CB2_P7_M3 As CheckBox
	Private CB3_P7_M3 As CheckBox
	Private CB4_P7_M3 As CheckBox
	Private CB1_P8_M3 As CheckBox
	Private CB2_P8_M3 As CheckBox
	Private CB4_P8_M3 As CheckBox
	Private RB1_P9_M3 As RadioButton
	Private RB2_P9_M3 As RadioButton
	Private RB3_P9_M3 As RadioButton
	Private RB4_P9_M3 As RadioButton
	Private RB5_P9_M3 As RadioButton
	Private B_guardaencuesta_m3 As Button
	Private P_gallina As Panel
	Private b_acepta_gallina As Button
	Private B_CANCELA_GALLINA As Button
	Private B_GALLINA As Button
	Private la_cuenta_gallina As Label
	Private cb_pregunta As B4XComboBox
	Dim girotienda As String
	Private p_pregunta1 As Panel
	Private b_preguntag As Button
	Private EN_QUE_ENCUESTA As String
	Private ENCUESTA As String
	Private et_p1_m4 As EditText
	Private et_p2_m4 As EditText
	Private cb_p3_m4 As B4XComboBox
	Private cb_p4_1_m4 As B4XComboBox
	Private cb_p4_2_m4 As B4XComboBox
	Private cb_p4_3_m4 As B4XComboBox
	Private cb_p4_4_m4 As B4XComboBox
	Private cb_p4_5_m4 As B4XComboBox
	Dim itemselect2 As String
	Dim itemselect3 As String
	Dim itemselect4 As String
	Dim itemselect5 As String
	Dim itemselect6 As String
	Dim itemselect7 As String
	Private B_guardaencuesta_m4 As Button
	Private p_modulo5 As Panel
	Private cb_p1_m5 As B4XComboBox
	Private cb_p2_m5 As B4XComboBox
	Private cb_p3_m5 As B4XComboBox
	Private cb_p4_m5 As B4XComboBox
	Private cb_p5_m5 As B4XComboBox
	Private cb_p6_m5 As B4XComboBox
	Private cb_p7_m5 As B4XComboBox
	Private cb_p8_m5 As B4XComboBox
	Private cb_p9_m5 As B4XComboBox
	Dim itemselect8 As String
	Dim itemselect9 As String
	Dim itemselect10 As String
	Dim itemselect11 As String
	Dim itemselect12 As String
	Dim itemselect13 As String
	Dim itemselect14 As String
	Dim itemselect15 As String
	Dim itemselect16 As String
	Private B_guardaencuesta_m5 As Button
	Dim PASA As String
	Private RB1_P4_M2 As RadioButton
	Private RB2_P4_M2 As RadioButton
	Private panel7_p4_m2 As Panel
	Private CB1_P4_M2 As CheckBox
	Private CB2_P4_M2 As CheckBox
	Private CB3_P4_M2 As CheckBox
	Private CB4_P4_M2 As CheckBox
	Private Panel4 As Panel
	Private B_GUARDA_CE_PED As Button
	
	
	Private KP_01 As CheckBox
	Private KP_02 As CheckBox
	Private KP_03 As CheckBox
	Private KP_04 As CheckBox
	Private KP_05 As CheckBox
	Private KP_06 As CheckBox
	Private KP_07 As CheckBox
	Private KP_08 As CheckBox
	Private KP_09 As CheckBox
	Private KP_10 As CheckBox
	Private KP_11 As CheckBox
	Private KP_12 As CheckBox
	Private KP_13 As CheckBox
	Private KP_14 As CheckBox
	Private KP_15 As CheckBox
	Private KP_16 As CheckBox
	Private KP_17 As CheckBox
	Private KP_18 As CheckBox
	Private KP_19 As CheckBox
	Private KP_20 As CheckBox
	
	Private KG_01 As CheckBox
	Private KG_02 As CheckBox
	Private KG_03 As CheckBox
	Private KG_04 As CheckBox
	Private KG_05 As CheckBox
	Private KG_06 As CheckBox
	
	Private PK_01 As CheckBox
	Private PK_02 As CheckBox
	Private PK_03 As CheckBox
	Private PK_04 As CheckBox
	Private PK_05 As CheckBox
	Private PK_06 As CheckBox
	Private PK_07 As CheckBox
	Private PK_08 As CheckBox
	
	Private HPG_01 As CheckBox
	Private HPG_02 As CheckBox
	Private HPG_03 As CheckBox
	Private HPG_04 As CheckBox
	Private HPG_05 As CheckBox
	Private HPG_06 As CheckBox
	Private HPG_07 As CheckBox
	Private HPG_08 As CheckBox
	Private HPG_09 As CheckBox
	Private HPG_10 As CheckBox
	
	Private HC_01 As CheckBox
	Private HC_02 As CheckBox
	Private HC_03 As CheckBox
	Private HC_04 As CheckBox
	
	Private B_01 As CheckBox
	Private B_02 As CheckBox
	
	Private CH_FACTURA As CheckBox
	Private que_modulo As String
	Private CUENTA_MODULO As String
	Private rb1_m3_p1 As RadioButton
	Private RB2_M3_P1 As RadioButton
	Private RB3_M3_P1 As RadioButton
	Private RB4_M3_P1 As RadioButton
	Private RB1_M3_P2 As RadioButton
	Private RB2_M3_P2 As RadioButton
	Private RB3_M3_P2 As RadioButton
	Private RB4_M3_P2 As RadioButton
	Private et_p2_m3_1 As EditText
	Dim textemp2 As String =""
	Dim textemp3 As String =""
	Dim textemp4 As String =""
	Dim textemp5 As String =""
	Dim textemp6 As String =""
	Dim textemp7 As String =""
	Dim textemp8 As String =""
	Private CB3_P8_M3 As CheckBox
	Private CB7_P6_M3 As CheckBox
	Private p_m1 As Panel
	Private p_m2 As Panel
	Private p_m3 As Panel
	Private p_m4 As Panel
	Dim impresoraConectada As Boolean = False
	Dim errorImpresora As Int = 0
	Dim idencuestaaguardar As String
	'Encuestas
	Private botonPresionado As Int
	Private encuestaRes As String
	Dim indicePregunta As Int
	Dim TOMAR_FOTO As String
	Dim CURSOR_FOTO As Int
	Dim id_encuesta As String
	Private chk_1_valor As String
	Private chk_2_valor As String
	Private chk_3_valor As String
	Private Panel10 As Panel
	Private b_chk_e As Button
	Private chk_3 As CheckBox
	Private chk_2 As CheckBox
	Private Chk_1 As CheckBox
	Private l_chk_e As Label
	Private Label28 As Label
	Private p_encuesta As Panel
	Private b_encuesta_continuar As Button
	Private b_encuesta_3 As Button
	Private b_encuesta_2 As Button
	Private b_encuesta_1 As Button
	Private et_encuesta As EditText
	Private l_txtEncuesta As Label
	Private l_titEncuesta As Label
	Private ImageView11 As ImageView
	Dim distance As Long
	Dim distancealm As Long
	Private p_pideGeoPass As Panel
	Private b_geopass As Button
	Private et_geopass As EditText
	Private l_geopass As Label
	Dim reqManager As DBRequestManager
	Dim ime As IME
	Private camEx As CameraExClass
	Dim frontCamera As Boolean = False
	Private p_cam As Panel
	Dim  nombrefoto As String = "0"
	Private p_camara As Panel
	Private teclado As IME
	Dim fototomada As String
	Private b_foto As Button
	Dim precision As String
	Dim b_Inicio_Fin_venta As Button
	
	Dim dentroDeGeocerca As Boolean = False
	Dim motivoNoVenta, motivoNoVisita As String
	Dim contadorIniciarVenta As Int = 0
	Dim IniVenNO As Boolean = False
	Private geoCont As Int = 0
	Private l_version As Label
	
'	Dim p_transparenteInicioFin As Panel
'	Dim b_geo As String

	Private b_preventa As Button
	Dim bitacora As C_Bitacora
	Dim p_transparenteTicketImpreso As Panel
	Private et_codigoAutorizacion As EditText
	Private b_codigoAutorizacion As Button
	Private b_cancelarCodigoAutorizacion As Button
	Private p_ticketImpreso As Panel
	Private b_enviarTicket As Button
	Dim archivoTicketPDF As String
	Private p_transparentePDF As Panel
	Private p_envioPDF As Panel
	Private b_cancelarEnvioPDF As Button
	Private b_envioPDF As Button
	Private et_numeroPDF As EditText
	Private btnPlanLealtad As Button
	Private pnl_btns As Panel
	Private pnlPlanLealtad As Panel
	Private imgPlanLealtad As ImageView
	Private btnAceptaPlanLealtad As Button
	Private btnCancelarPlanLealtad As Button
	Private BCREDITO As String
	
	
	Private p_comentarios As Panel
	Private p_comentario As Panel
	Private b_agregarcom As Button
	Private b_cerarcom As Button
	Private Label19 As Label
	Private et_comentario As EditText
	Private lv_comentarios As ListView
	Private ImageView4 As ImageView
	Private p_cliente_ As Panel
	Private l_limite As Label
	Private l_credito As Label
	Private l_tipocliente As Label
	Private l_deuda As Label
	Private p_deuda As Panel
	Private Label22 As Label
	Private l_animal As Label
	Private contIguales As Int = 0
	Private b_preventa2 As Button
	Private p_atiende As Panel
	Private et_atiende As EditText
	Private b_cancelatiende As Button
	Private b_acepatiende As Button
	Private p_telefono As Panel
	Private b_canceltelefono As Button
	Private b_aceptelefono As Button
	Private et_telefono As EditText
	
	Dim totalpromos As Double
	Dim totalpromostotal As Double
	Private chb_com As CheckBox
	
	Private P_Imagengrande As Panel
	Private I_fotogrande As ImageView
	
	
	Private scv_bat As ScrollView
	Private b_cancelencu As Button
	Private b_guadarenc As Button
	Private p_encu As Panel
	Private cb_p1 As B4XComboBox
	Private cb_p2 As B4XComboBox
	Private cb_p3 As B4XComboBox
	Private cb_p4 As B4XComboBox
	Private cb_p5 As B4XComboBox
	Dim e_1, e_2, e_3, e_4,e_5,e_6,e_7,e_8,e_9,e_10 As String
	Private cb_p6 As B4XComboBox
	Private cb_p7 As B4XComboBox
	Private cb_p8 As B4XComboBox
	Private cb_p9 As B4XComboBox
	Private cb_p10 As B4XComboBox
End Sub

'You can add more parameters here.
Public Sub Initialize As Object
	Return Me
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	'load the layout to Root
'	Activity.RemoveAllViews
	Root.LoadLayout("cliente")
	ruta = File.DirInternal
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
	End If
	skmt.Initialize(ruta,"kmt.db", True)
	c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA  from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	s=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position=0
	If c.RowCount>0 Then
		c.Position=0
		la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
		cuenta = c.GetString("CAT_CL_CODIGO")
		La_nombre.Text = c.GetString("CAT_CL_NOMBRE")
		la_Calle.Text = c.GetString("CAT_CL_CALLE") & c.GetString("CAT_CL_NOEXT")
		la_col.Text = c.GetString("CAT_CL_COLONIA")
		la_edo.Text = c.GetString("CAT_CL_EDO")
'			 la_cp.Text = c.GetString("CAT_CL_CP")
		l_entre1.Text = c.GetString("CAT_CL_CALLE1")
		l_entre2.Text = c.GetString("CAT_CL_CALLE2")
		l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
		l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
		la_saldotot.Text = c.GetString("CAT_CL_TELEFONO")
		la_saldooper.Text = c.GetString("CAT_CL_EMAIL")
		l_total.Text = s.GetString("TOTAL_CLIE")
		total_cliente = s.GetString("TOTAL_CLIE")
		MONTO_COMPRA = c.GetString("CAT_CL_MTOCOMPRA")
	End If
	c.Close
	s.Close
	File.Copy(File.DirAssets,"guna-fondo.jpg",xui.DefaultFolder,"guna-fondo.jpg")
	TOMAR_FOTO = 0
	btAdmin.Initialize("BlueTeeth")
	cmp20.Initialize("Printer")
	SV_ENCUESTA.Height = Root.Height
	SV_ENCUESTA.Width = Root.Height
	p_pregunta1.Height = Root.Height
	p_pregunta1.Width = Root.Height
	p_transparenteTicketImpreso.Left = 0 : p_transparenteTicketImpreso.top = 0
	p_transparentePDF.Left = 0 : p_transparentePDF.top = 0
	p_transparenteTicketImpreso.Width = Root.Width : p_transparenteTicketImpreso.Height = Root.Height
	p_transparentePDF.Width = Root.Width : p_transparentePDF.Height = Root.Height
	Subs.centraPanel(p_ticketImpreso, p_transparenteTicketImpreso.Width)
	Subs.centraPanel(p_envioPDF, p_transparentePDF.Width)
	p_comentario.Left = 0 : p_comentario.top = 0
	p_comentario.Width = Root.Width : p_comentario.Height = Root.Height
	Subs.centraPanel(p_comentarios, p_comentario.Width)
	Tels.Visible = False
	gest.Visible = False
	b_preventa2.Visible = False
	l_version.Left = Root.Width - (l_version.Width + 10)
	cuest.Initialize(Me, "cuest", Root, B4XPages.MainPage.skmt)
	bitacora.Initialize("bitacora", "bitacora", Root, B4XPages.MainPage.skmt, reqManager)
	l_version.Left = Root.Width - l_version.Width
'	bitacora.cargamosPanel
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub B4XPage_Appear
	Starter.enCliente = True
	Tels.Visible = False
	gest.Visible = False
	b_preventa2.Visible = False
'	Tels.Enabled = True
'	gest.Enabled = True
'	MejorarPrecisionGPS
'	' Al aparecer la página del cliente
'	InicializarLocalizacionMejorada
	B4XPages.MainPage.skmt.ExecNonQuery("delete from PEDIDO where PE_CANT <= 0")
	recalculoXcant

	ImageView4.Bitmap = LoadBitmap(File.DirAssets,"images.png")
	btnPlanLealtad.Visible = False
	bitacora.inicioFin
'	iniciofin
	que_modulo = 1
	scv_bat.Width = Root.Width
	scv_bat.Height = Root.Height
	dentroDeGeocerca = False
	indicePregunta = 0
	l_credito.Visible = False
	l_limite.Visible = False
	pnlPlanLealtad.Top = 0
	pnlPlanLealtad.Left = 0
	pnlPlanLealtad.Width = Root.Width
	pnlPlanLealtad.Height = Root.Height
	p_cliente.Width = Root.Width
	p_cliente.Height = Root.Height
	p_cliente_.Width = Root.Width
	Subs.centraPanel(p_atiende, Root.Width)
	Subs.centraPanel(p_telefono, Root.Width)
	
	
	If TOMAR_FOTO <> 0 Then Cuestionario
	Starter.idCliente = Subs.traeCliente
'	Log(Subs.traeCliente)
	If Subs.traeCliente = "0" Then
		tipo_venta = "ABORDO"
		Log(1)
		Log("ABORDO")
	Else
		tipo_venta = Subs.traeTipoVentaDeBD
'		Log(2)
		Log(Subs.traeTipoVentaDeBD)
	End If
	B4XPages.MainPage.tipo_venta = tipo_venta
	Log($"TIPO_VENTA: ${tipo_venta}"$)
	encuentasmapa.Initialize
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
	Wait For B4XPage_PermissionResult (Permission As String, resultC As Boolean)
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
	Wait For B4XPage_PermissionResult (Permission As String, resultC As Boolean)
	LA_GPS.TextColor = Colors.Red
	LA_GPS.Text = "SIN UBICACION GPS"
	cercavalor = 0
	l_version.Text = Application.VersionName
	b_preventa.left = (Root.Width / 2) - (b_preventa.width / 2)
'	p_transparenteInicioFin.Width = Root.Width : p_transparenteInicioFin.Height = Root.Height
'	b_Inicio_Fin_venta.Left = 5
'	b_Inicio_Fin_venta.Width = Root.Width - 10
'	b_Inicio_Fin_venta.Text = "INICIAR VENTA"
'	b_Inicio_Fin_venta.BringToFront
'	LogColor(">>>>>> EN VENTA: " & Starter.enVenta, Colors.red)
'	If Not(Starter.enVenta) Then
'		b_Inicio_Fin_venta.Visible = True
'		Log("EnVenta Visible")
'	Else
'		Log("EnVenta NO Visible")
'		b_Inicio_Fin_venta.Visible = False
'	End If

	If Subs.hayPedido Then 'Si hay pedido, deshabilitamos el boton de "No Venta"
		Log(">>>>>     HAY PEDIDO")
		Tels.Enabled = False
	Else
		Tels.Enabled = True
	End If

	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	skmt.Initialize(ruta,"kmt.db", True)
	reqManager.Initialize(Me, Starter.server)

'	Dim fotomostrar As Cursor = Starter.skmt.ExecQuery("SELECT foto FROM kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
'	If fotomostrar.RowCount > 0 Then
'		Dim fotomostrar1 As Cursor = Starter.skmt.ExecQuery("SELECT foto FROM kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) AND foto IS NULL")
'		If fotomostrar1.RowCount > 0 Then
'			ImageView4.Bitmap = LoadBitmap(File.DirAssets,"images.png")
'			Log("aqui no hay foto")
'		Else
'			fotomostrar.Position = 0
'			Private fotomostrarfinal() As Byte = fotomostrar.GetBlob("foto")
'			Dim InputStream1 As InputStream
'			InputStream1.InitializeFromBytesArray(fotomostrarfinal, 0, fotomostrarfinal.Length)
'			Dim Bitmap1 As Bitmap
'			Bitmap1.Initialize2(InputStream1)
'			InputStream1.Close
'			ImageView4.Bitmap = Bitmap1
'			Log("aqui si hay foto")
'		End If
'	End If
	Subs.centraPanel(P_Imagengrande,Root.Width)
	B4XPages.MainPage.skmt.ExecNonQuery("delete from PEDIDO where PE_CLIENTE In (select cuenta from cuentaa) AND PE_CANT <= 0")
		
	Dim fotomostrar1 As Cursor = Starter.skmt.ExecQuery("SELECT foto FROM kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) AND foto IS NOT NULL")
	If fotomostrar1.RowCount = 0 Then
			
		Dim fotomostrar As Cursor = Starter.skmt.ExecQuery("SELECT FOTO FROM FOTOS where CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		If fotomostrar.RowCount > 0 Then
		
			fotomostrar.Position = 0
			Private fotomostrarfinal() As Byte = fotomostrar.GetBlob("FOTO")
			Dim InputStream1 As InputStream
			InputStream1.InitializeFromBytesArray(fotomostrarfinal, 0, fotomostrarfinal.Length)
			Dim Bitmap1 As Bitmap
			Bitmap1.Initialize2(InputStream1)
			InputStream1.Close
			ImageView4.Bitmap = Bitmap1
			Log("aqui si hay foto")
		Else
			ImageView4.Bitmap = LoadBitmap(File.DirAssets,"images.png")
			Log("aqui no hay foto")
		End If
			
	Else
		fotomostrar1.Position = 0
		Private fotomostrarfinal() As Byte = fotomostrar1.GetBlob("foto")
		Dim InputStream1 As InputStream
		InputStream1.InitializeFromBytesArray(fotomostrarfinal, 0, fotomostrarfinal.Length)
		Dim Bitmap1 As Bitmap
		Bitmap1.Initialize2(InputStream1)
		InputStream1.Close
		ImageView4.Bitmap = Bitmap1
		Log("aqui si hay foto")
	End If
		
'			ImageView4.Bitmap = LoadBitmap(File.DirAssets,"images.png")
'			Log("aqui no hay foto")
		


	l_tipocliente.Text = Subs.traeTipoCliente
	p_camara.Width = Root.Width
	p_camara.Height = Root.Height
	S2=B4XPages.MainPage.skmt.ExecQuery("select count(*) AS CUANTOS from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa)")
	S2.Position =0
	CUANTOS = S2.GetString("CUANTOS")
	S2.Close
	If CUANTOS > 0 Then
		c2=B4XPages.MainPage.skmt.ExecQuery("select sum(HVD_COSTO_TOT) AS TOTAL from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa)")
		c2.Position =0
		MONTO_COMPRA = c2.GetString("TOTAL")
		c2.Close
	Else
		MONTO_COMPRA = "0"
	End If
	la_saldotot.Text = MONTO_COMPRA
	If MONTO_COMPRA <> "0" Then
		META2 = 300 -  MONTO_COMPRA
	Else
		META2 = 300
	End If
	If META2 < 1 Then
		META2 = "CUBIERTO"
	End If
	If IsNumber(META2) Then META2 = NumberFormat2(META2, 0, 2, 2, True)
	la_saldooper.Text = META2
	c=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	If c.RowCount>0 Then
		C.Position=0
		ALMACEN = C.GetString("ID_ALMACEN")
	End If
	c.Close

	If ALMACEN = "1" Then
		Tels.Visible = False
		gest.Visible = True
		B_GPS.Visible = False
	End If
	If ALMACEN = "4"  Then
		b_like.Visible = False
		DD=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select cuenta from cuentaa) AND HVD_PRONOMBRE =?", Array As String("KNORR RINDE MAS 70 GR"))
		DD.Position =0
		If DD.GetString("CUANTOS")  = 0 Then
			c=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (Select cuenta from cuentaa) AND PE_PRONOMBRE =?", Array As String("KNORR RINDE MAS 70 GR"))
			c.Position =0
			If c.GetString("CUANTOS") = 0 Then
				b_like.Visible = False
			Else
				b_like.Visible = False
			End If
			c.Close
		Else
			b_like.Visible = False
		End If
		DD.Close
	Else
		b_like.Visible = False
	End If
	If ALMACEN = "16" Or ALMACEN = "13" Then
		Tels.Visible = True
		gest.Visible = True
	End If
	c = skmt.ExecQuery("SELECT PC_CLIENTE  FROM PEDIDO_CLIENTE WHERE PC_CLIENTE IN (Select CUENTA from cuentaa)")
	If c.RowCount > 0 Then
		Tels.Visible = True
		gest.Visible = True
		Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
		If future.RowCount > 0 Then
			future.Position = 0
			If future.GetInt("CAT_VA_VALOR") = 1 Then
				b_preventa2.Visible = True
			Else If future.GetInt("CAT_VA_VALOR") = 0 Then
				b_preventa2.Visible = False
			End If
		End If
		
	Else If c.RowCount = 0 Then
		Tels.Visible = False
		gest.Visible = False
		
		b_preventa2.Visible = False
		
		c = skmt.ExecQuery("SELECT NV_CLIENTE FROM NOVENTA CLIENTE WHERE NV_CLIENTE IN (Select CUENTA from cuentaa)")
		If c.RowCount > 0 Then
			Tels.Visible = True
			gest.Visible = True
			Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
			If future.RowCount > 0 Then
				future.Position = 0
				If future.GetInt("CAT_VA_VALOR") = 1 Then
					b_preventa2.Visible = True
				Else If future.GetInt("CAT_VA_VALOR") = 0 Then
					b_preventa2.Visible = False
				End If
			End If
		Else If c.RowCount = 0 Then
			Tels.Visible = False
			gest.Visible = False
			b_preventa2.Visible = False
			LA_GEO.TextColor = Colors.Red
			If ALMACEN = "1" Then
				Tels.Visible = False
				gest.Visible = True
			End If
		End If
		LA_GEO.TextColor = Colors.Red
		If ALMACEN = "1" Then
			Tels.Visible = False
			gest.Visible = True
		End If
	End If
'	CallSubDelayed(Tracker, "Track")
	CallSubDelayed(Tracker, "StartFLPSmall")
'	CallSubDelayed(Tracker, "StartFLP2")
	If Tracker.FLP.GetLastKnownLocation.IsInitialized Then 'Si tenemos "UltimaUbicaccionConocida" la usamos.
		B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
		B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
		Log($"Tenemos UUC: ${Tracker.FLP.GetLastKnownLocation.Latitude},${Tracker.FLP.GetLastKnownLocation.Longitude}"$)
		GPS_LocationChanged(Tracker.FLP.GetLastKnownLocation)
	End If
	If ALMACEN = "1" Or ALMACEN = "2" Or ALMACEN = "4" Or ALMACEN = "5" Or ALMACEN = "25" Then
		DD=skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM HIST_VENTAS WHERE HVD_CLIENTE IN (Select cuenta from cuentaa) AND HVD_PRONOMBRE =?", Array As String("KNORR SUIZA GALLINA"))
		DD.Position =0
		If DD.GetString("CUANTOS")  = 0 Then
			c=skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM PEDIDO  WHERE PE_CLIENTE  IN (Select cuenta from cuentaa) AND PE_PRONOMBRE =?", Array As String("KNORR SUIZA GALLINA"))
			c.Position =0
			If c.GetString("CUANTOS") = 0 Then
				B_GALLINA.Visible = True
			Else
				B_GALLINA.Visible = False
			End If
			c.Close
		Else
			B_GALLINA.Visible = False
		End If
		DD.Close
	Else
		B_GALLINA.Visible = False
	End If
	P_gallina.Visible = False
	B_GALLINA.Visible = False
	que_modulo = 1
	If ALMACEN = "2" Or ALMACEN = "4" Or  ALMACEN = "5"  Or ALMACEN = "4" Or  ALMACEN = "53" Or  ALMACEN = "64" Or  ALMACEN = "25" Then
		b_like.Visible = True
	Else
		b_like.Visible = False
	End If
	c = skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP"))
	If c.RowCount > 0 Then
		c.Position = 0
		Starter.MAC_IMPRESORA = c.GetString("CAT_VA_VALOR")
	End If
	If Starter.MAC_IMPRESORA = "" Then Starter.MAC_IMPRESORA = "0"
'	Log("|" & Starter.MAC_IMPRESORA & "|")
	Printer1.Initialize(Me, "Printer1")

	If Printer1.IsConnected = False Then
'		Printer1.Connect
'		Log("1")
	Else
		Printer1.DisConnect
		Printer1.Connect
		Log("2")
	End If
	c = skmt.ExecQuery("SELECT HABILITADA FROM IMPRESORA")
	If c.RowCount >  0 Then
		c.Position = 0
		If c.GetString("HABILITADA") = 1 Then
			B_IMP.Visible = True
		Else If c.GetString("HABILITADA") = 0 Then
			B_IMP.Visible = False
		End If
	Else If c.RowCount =  0 Then
		B_IMP.Visible = False
	End If
'	Log(distance)
'	LogColor(">>>>>> EN VENTA: " & Starter.enVenta, Colors.red)
'	Log(Subs.InvSuficientePromoEsp)
'	Log(Subs.traemontoprod)
	If ALMACEN = 32 Then
		If Subs.traemontoprod And Subs.InvSuficientePromoEsp And Not(Subs.vendidoPromoEsp) Then
			Msgbox2Async("El cliente tiene derecho a una promo por la compra de mas de $120 en productos Helmanns, Maizena y/o Knorr" , "Promo disponible", "Aceptar", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				B4XPages.MainPage.productos.terminarpromoesp
			End If
		Else
		End If
		If Not(Subs.traemontoprod) And Subs.vendidoPromoEsp Then
			Private j3 As Cursor
			Log("SI PROMO")
			j3 = B4XPages.MainPage.skmt.ExecQuery2("SELECT PE_CEDIS, PE_CANT,PE_PROID, PE_PRONOMBRE FROM PEDIDO WHERE PE_CEDIS IN (SELECT PE_CEDIS FROM PEDIDO WHERE PE_PROID = ?)",Array As String("PROUNI01"))
			Log(j3.RowCount)
			If j3.RowCount = 0 Then
				Log("estoy aqui")
				For i = 0 To j3.RowCount -1
					Log("aqui tronare?")
					j3.Position = i
					B4XPages.MainPage.skmt.ExecNonQuery($"update ${Subs.traeTablaProds(tipo_venta)} set cat_gp_almacen = cat_gp_almacen + ${j3.GetString("PE_CANT")} where cat_gp_id = '${j3.Getstring("PE_PROID")}'"$)
					B4XPages.MainPage.skmt.ExecNonQuery2("delete from pedido where  pe_cedis in (select pe_cedis from pedido where pe_pronombre = ?) and pe_cliente in (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As Object(j3.GetString("PE_PRONOMBRE"), tipo_venta))
				Next
			End If
			j3.Close
		Else
		End If
	End If

	If ALMACEN = 87 Or ALMACEN = 6 Then
		If Subs.traemontoprod And Subs.traeCliente <> "0" Then
			Msgbox2Async("El cliente tiene derecho a un descuento de 150 pesos por la compra de mas de $500 en productos participantes" , "Descuento disponible", "Aceptar", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT SUM(PE_CANT) AS PIEZAS FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA)")
				If c.RowCount > 0 Then
					c.Position = 0
					Private des As Float = NumberFormat2(150/c.GetString("PIEZAS"),0,2,2,False)
					Log( NumberFormat2(des,0,2,2,False))
					Private c2 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT Ifnull(SUM(PE_CANT),0) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU < ?",Array As String(des))
					If c2.RowCount > 0 Then
						c2.Position = 0
						Log(c2.GetString("PE_CANT"))
					End If
					Private c3 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT SUM(PE_CANT) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(des))
					If c3.RowCount > 0 Then
						c3.Position = 0
						Log(c3.GetString("PE_CANT"))
						Private rec As Float = (des * c2.GetString("PE_CANT"))/c3.GetString("PE_CANT")
						Log( NumberFormat2(rec,0,2,2,False))
						Private cantres As Float = des + rec
						Log( NumberFormat2(cantres,0,2,2,False))
						Private c5 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT Ifnull(SUM(PE_CANT),0) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU > ? and PE_COSTOU < ?",Array As String(des, cantres))
						If c5.RowCount > 0 Then
							c5.Position = 0
							Log(c5.GetString("PE_CANT"))
							If c5.GetString("PE_CANT") = "0" Then
								Private c4 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(NumberFormat2(cantres,0,2,2,False)))
								If c4.RowCount > 0 Then
									For i = 0 To c4.RowCount -1
										c4.Position = i
										Private recalculo As Float = c4.GetString("PE_COSTOU") - NumberFormat2(cantres,0,2,2,False)
										LogColor(recalculo,Colors.Blue)
										Private recalculototal As Float = c4.GetString("PE_CANT") * NumberFormat2(recalculo,0,2,2,False)
'								Log(recalculo&"|||||"&recalculototal)
										skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = ?, PE_RECALCULOTOT = ? WHERE PE_PROID = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) ",Array As String(NumberFormat2(recalculo,0,2,2,False) ,NumberFormat2(recalculototal,0,2,2,False), c4.GetString("PE_PROID")))
									Next
								End If
								c4.Close
							Else
								Private c6 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT SUM(PE_CANT) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(cantres))
								If c6.RowCount > 0 Then
									c6.Position = 0
									Log(c6.GetString("PE_CANT"))
									Private rec1 As Float = (cantres * c5.GetString("PE_CANT"))/c6.GetString("PE_CANT")
									Log( NumberFormat2(rec1,0,2,2,False))
									Private cantres1 As Float = cantres + rec1
									Log( NumberFormat2(cantres1,0,2,2,False))
									Private c4 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(NumberFormat2(cantres1,0,2,2,False)))
									If c4.RowCount > 0 Then
										For i = 0 To c4.RowCount -1
											c4.Position = i
											Private recalculo As Float = c4.GetString("PE_COSTOU") - NumberFormat2(cantres1,0,2,2,False)
											LogColor(recalculo,Colors.Blue)
											Private recalculototal As Float = c4.GetString("PE_CANT") * NumberFormat2(recalculo,0,2,2,False)
'								Log(recalculo&"|||||"&recalculototal)
											skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = ?, PE_RECALCULOTOT = ? WHERE PE_PROID = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) ",Array As String(NumberFormat2(recalculo,0,2,2,False) ,NumberFormat2(recalculototal,0,2,2,False), c4.GetString("PE_PROID")))
										Next
									End If
									c4.Close
								End If
							End If
						End If
					End If
				End If
			End If
			c.Close
			c2.Close
			c3.Close
		Else If Subs.traemontoprod2 And Subs.traeCliente <> "0" Then
			Msgbox2Async("El cliente tiene derecho a un descuento de 70 pesos por la compra de mas de $350 en productos participantes" , "Descuento disponible", "Aceptar", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT SUM(PE_CANT) AS PIEZAS FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA)")
				If c.RowCount > 0 Then
					c.Position = 0
					Private des As Float = NumberFormat2(70/c.GetString("PIEZAS"),0,5,5,False)
					Log(des)
					Private c2 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT Ifnull(SUM(PE_CANT),0) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU < ?",Array As String(des))
					If c2.RowCount > 0 Then
						c2.Position = 0
						Log(c2.GetString("PE_CANT"))
					End If
					Private c3 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT SUM(PE_CANT) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(des))
					If c3.RowCount > 0 Then
						c3.Position = 0
						Log(c3.GetString("PE_CANT"))
						Private rec As Float = (des * c2.GetString("PE_CANT"))/c3.GetString("PE_CANT")
						Log( NumberFormat2(rec,0,2,2,False))
						Private cantres As Float = des + rec
						Log( NumberFormat2(cantres,0,2,2,False))
						Private c5 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT Ifnull(SUM(PE_CANT),0) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU > ? and PE_COSTOU < ?",Array As String(des, cantres))
						If c5.RowCount > 0 Then
							c5.Position = 0
							Log(c5.GetString("PE_CANT"))
							If c5.GetString("PE_CANT") = "0" Then
								Private c4 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(NumberFormat2(cantres,0,2,2,False)))
								If c4.RowCount > 0 Then
									For i = 0 To c4.RowCount -1
										c4.Position = i
										Private recalculo As Float = c4.GetString("PE_COSTOU") - NumberFormat2(cantres,0,2,2,False)
										LogColor(recalculo,Colors.Blue)
										Private recalculototal As Float = c4.GetString("PE_CANT") * NumberFormat2(recalculo,0,2,2,False)
										Log(recalculo&"|||||"&recalculototal&"|||||||||||||||||||"&c4.GetString("PE_PROID"))
										skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = ?, PE_RECALCULOTOT = ? WHERE PE_PROID = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) ",Array As String(NumberFormat2(recalculo,0,2,2,False) ,NumberFormat2(recalculototal,0,2,2,False), c4.GetString("PE_PROID")))
									Next
								End If
								c4.Close
							Else
								Private c6 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT SUM(PE_CANT) AS PE_CANT FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(cantres))
								If c6.RowCount > 0 Then
									c6.Position = 0
									Log(c6.GetString("PE_CANT"))
									Private rec1 As Float = (cantres * c5.GetString("PE_CANT"))/c6.GetString("PE_CANT")
									Log( NumberFormat2(rec1,0,2,2,False))
									Private cantres1 As Float = cantres + rec1
									Log( NumberFormat2(cantres1,0,2,2,False))
									Private c4 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_COSTOU >= ?",Array As String(NumberFormat2(cantres1,0,2,2,False)))
									If c4.RowCount > 0 Then
										For i = 0 To c4.RowCount -1
											c4.Position = i
											Private recalculo As Float = c4.GetString("PE_COSTOU") - NumberFormat2(cantres1,0,2,2,False)
											LogColor(recalculo,Colors.Blue)
											Private recalculototal As Float = c4.GetString("PE_CANT") * NumberFormat2(recalculo,0,2,2,False)
'								Log(recalculo&"|||||"&recalculototal)
											skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = ?, PE_RECALCULOTOT = ? WHERE PE_PROID = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) ",Array As String(NumberFormat2(recalculo,0,2,2,False) ,NumberFormat2(recalculototal,0,2,2,False), c4.GetString("PE_PROID")))
										Next
									End If
									c4.Close
								End If
							End If
						End If
					End If
				End If
			End If
			c.Close
			c2.Close
			c3.Close
		End If
		If Not(Subs.traemontoprod)  Then
			If Not(Subs.traemontoprod2) Then
				Private c4 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO JOIN CAT_PROMO_ESP ON CAT_PE_ID = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND (PE_RECALCULO <> ? OR PE_RECALCULO IS NOT NULL)",Array As String("null"))
				If c4.RowCount > 0 Then
					For i = 0 To c4.RowCount -1
						c4.Position = i
'					Private recalculo As Float = c4.GetString("PE_COSTOU") - NumberFormat2(cantres,0,2,2,False)
'					Private recalculototal As Float = c4.GetString("PE_CANT") * NumberFormat2(recalculo,0,2,2,False)
'					Log(recalculo&"|||||"&recalculototal)
						B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = ?, PE_RECALCULOTOT = ? WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND PE_PROID = ? ",Array As String("","",c4.GetString("PE_PROID")))
					Next
				End If
			Else
			End If
		Else
			
		End If
	End If

	'AQUI CAMBIAR
	Private s3 As Cursor=B4XPages.MainPage.skmt.ExecQuery2("select * FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_RECALCULO <> ? OR PE_RECALCULO <> ? OR PE_RECALCULO IS NOT NULL",Array As String("","null"))
'	LogColor(s3.RowCount,Colors.Yellow)
	If s3.RowCount > 0 Then
		'##########################  CODIGO PARA CREDITOS ####################
		c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		s=B4XPages.MainPage.skmt.ExecQuery2("select iFNULL(sum(pe_costo_tot),0) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and (PE_RECALCULO = ? or PE_RECALCULO = ? or PE_RECALCULO IS NULL)",Array As String("","null"))
		s.Position=0
		Private s5 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select iFNULL(sum(PE_RECALCULOTOT),0) as TOTAL_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and (PE_RECALCULO <> ? or PE_RECALCULO <> ? OR PE_RECALCULO IS NOT NULL)",Array As String("","null"))
		s5.Position = 0
		If c.RowCount > 0 Then
			c.Position = 0
			Log(">>>>>>  " & c.GetString("CAT_CL_CODIGO"))
			la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
			la_cuenta_gallina.Text = c.GetString("CAT_CL_CODIGO")
			La_nombre.Text = c.GetString("CAT_CL_NOMBRE")
			la_Calle.Text = c.GetString("CAT_CL_CALLE") & " " & c.GetString("CAT_CL_NOEXT")
			la_col.Text = c.GetString("CAT_CL_COLONIA")
			la_edo.Text = c.GetString("CAT_CL_EDO")
			l_entre1.Text = c.GetString("CAT_CL_CALLE1")
			l_entre2.Text = c.GetString("CAT_CL_CALLE2")
			l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
			l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
			telefono  = c.GetString("CAT_CL_TELEFONO")
			Label19.Text = c.GetString("CAT_CL_TELEFONO")
			BCREDITO = c.GetString("CAT_CL_BCREDITO") '##########################  CODIGO PARA CREDITOS ####################

			If s.GetString("TOTAL_CLIE") = Null Then
				l_total.Text = 0
			Else
				l_total.Text =NumberFormat2((s.GetString("TOTAL_CLIE") + s5.GetString("TOTAL_CLIE")),0,2,2,False)
			End If
			total_cliente = s.GetString("TOTAL_CLIE") + s5.GetString("TOTAL_CLIE")
			m_lat = "0"
			If c.GetString("CAT_CL_LAT") <> "" Then m_lat =c.GetString("CAT_CL_LAT")
			If m_lat.Length < 5 Then m_lat = "0"
			m_lon = "0"
			If c.GetString("CAT_CL_LONG") <> "" Then m_lon =c.GetString("CAT_CL_LONG")
			If m_lon.Length < 5 Then m_lon = "0"
			LA_RUTA = c.GetString("CAT_CL_RUTA")
			' ESTO ES PARA FORZAR A PEDIR LA FOTO Y EL GPS
			If c.GetString("CAT_CL_NUM_SERIEFISICO") = "0"  Then
				L_QR.TEXT = "SIN CODIGO"
				L_QR.TextColor = Colors.Red
				If ALMACEN <> "32" And ALMACEN <> "33" And ALMACEN <> 6 Then  gest.VISIBLE = True And Tels.Visible = True
				BT_QR.Visible = True
			Else
				L_QR.TEXT = c.GetString("CAT_CL_NUM_SERIEFISICO")
				L_QR.TextColor = Colors.Blue
				BT_QR.Visible = False
			End If
		End If
		c.Close
		s.Close
	Else If s3.RowCount = 0 Then
		'##########################  CODIGO PARA CREDITOS ####################
		c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		s=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
		s.Position=0
		If c.RowCount > 0 Then
			c.Position=0
			la_cuenta.Text = c.GetString("CAT_CL_CODIGO")
			la_cuenta_gallina.Text = c.GetString("CAT_CL_CODIGO")
			La_nombre.Text = c.GetString("CAT_CL_NOMBRE")
			la_Calle.Text = c.GetString("CAT_CL_CALLE") & " " & c.GetString("CAT_CL_NOEXT")
			la_col.Text = c.GetString("CAT_CL_COLONIA")
			la_edo.Text = c.GetString("CAT_CL_EDO")
			l_entre1.Text = c.GetString("CAT_CL_CALLE1")
			l_entre2.Text = c.GetString("CAT_CL_CALLE2")
			l_atiende.Text = c.GetString("CAT_CL_ATIENDE1")
			l_atiende2.Text = c.GetString("CAT_CL_ATIENTE2")
			telefono  = c.GetString("CAT_CL_TELEFONO")
			Label19.Text = c.GetString("CAT_CL_TELEFONO")
			BCREDITO  = c.GetString("CAT_CL_BCREDITO") '##########################  CODIGO PARA CREDITOS ####################

'			Log(s.GetString("TOTAL_CLIE"))
			If s.GetString("TOTAL_CLIE") = Null Then
				l_total.Text = 0
			Else
				l_total.Text =NumberFormat2(s.GetString("TOTAL_CLIE"),0,2,2,False)
			End If
			total_cliente = s.GetString("TOTAL_CLIE")
			m_lat = "0"
			If c.GetString("CAT_CL_LAT") <> "" Then m_lat = c.GetString("CAT_CL_LAT")
			If m_lat.Length < 5 Then m_lat = "0"
			m_lon = "0"
			If c.GetString("CAT_CL_LONG") <> "" Then m_lon =c.GetString("CAT_CL_LONG")
			If m_lon.Length < 5 Then m_lon = "0"
			LA_RUTA = c.GetString("CAT_CL_RUTA")
			' ESTO ES PARA FORZAR A PEDIR LA FOTO Y EL GPS
			If c.GetString("CAT_CL_NUM_SERIEFISICO") = "0"  Then
				L_QR.TEXT = "SIN CODIGO"
				L_QR.TextColor = Colors.Red
				If ALMACEN <> "32" And ALMACEN <> "33" And ALMACEN <> 6 Then  gest.VISIBLE = True And Tels.Visible = True
				BT_QR.Visible = True
			Else
				L_QR.TEXT = c.GetString("CAT_CL_NUM_SERIEFISICO")
				L_QR.TextColor = Colors.Blue
				BT_QR.Visible = False
			End If
		End If
		c.Close
		s.Close
	End If
'	ToastMessageShow(BCREDITO, False)
	'AQUI TERMINA
	Starter.idCliente = la_cuenta.text
	c = skmt.ExecQuery("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'GEOCERCA'")
	If c.RowCount > 0 Then
		c.Position = 0
		Dim geo As String = c.GetString("CAT_VA_VALOR")
	End If
	c.Close
'	Log(geo)
	If geo = "0" Then
		gest.Visible = True
		Tels.Visible = True
		Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
		If future.RowCount > 0 Then
			future.Position = 0
			If future.GetInt("CAT_VA_VALOR") = 1 Then
				b_preventa2.Visible = True
			Else If future.GetInt("CAT_VA_VALOR") = 0 Then
				b_preventa2.Visible = False
			End If
		End If
'		b_Inicio_Fin_venta.Visible = True
		precision = "1"
'		Log("Hacemos visible el boton de Inicio Venta")
	Else If geo = "1" And distance > 100 Then
		gest.Visible = False
		b_preventa2.Visible = False
		Tels.Visible = False
		If b_Inicio_Fin_venta.IsInitialized Then
			
			b_Inicio_Fin_venta.Visible = False
		End If
'		ToastMessageShow("aaa", False)
	End If
	gest.Typeface =Typeface.CreateNew(Typeface.FONTAWESOME, Typeface.STYLE_BOLD)
	gest.Text = "  Preventa"
	If Subs.traeTipoVentaDeBD = "VENTA" Then gest.Text = "  Venta"
'	Log($">>>>>>>>>>    |${la_cuenta.Text.trim}|"$)
	If la_cuenta.Text.trim = "0" Then gest.Text = "Carga Abordo"
'	Log($"ALMACEN: ${ALMACEN}${CRLF}RUTA:${LA_RUTA}"$)
	Log(Subs.traeRuta)
	If Subs.hayPedido Then
		B_IMP.Enabled = True
		b_enviarTicket.Enabled = False
	Else
		B_IMP.Enabled = False
		b_enviarTicket.Enabled = False
	End If

	If ALMACEN = 46 Or ALMACEN = 6 Then
		c = Starter.skmt.ExecQuery("SELECT IfNull(PL_BANDERA, 0) AS PL_BANDERA FROM PLAN_LEALTAD WHERE PL_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		If c.RowCount > 0 Then
			c.Position = 0
			If c.GetString("PL_BANDERA") = 0 Then
				btnPlanLealtad.Visible = True
			Else
				btnPlanLealtad.Visible = False
			End If
		Else
			btnPlanLealtad.Visible = True
		End If
	Else
		btnPlanLealtad.Visible = False
	End If

'		fotomostrar.Position = 0
'		Private imagencompara() As Byte
'		imagencompara = fotomostrar.GetBlob("foto")
''		Log(imagencompara.Length)
'		If imagencompara.Length = Null Then
''			ImageView4 = fotomostrar.GetBlob("foto")
'			Log("LO LOGRAMOS")
'		End If
	If ALMACEN = 88 Then
		If Not(Subs.TraeMontoProd) Then
			B4XPages.MainPage.skmt.ExecNonQuery2("delete from pedido where  pe_cedis = 'MYKONOS_01' and pe_cliente in (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As Object(tipo_venta))
'			B4XPage_Appear
			Private s3 As Cursor=B4XPages.MainPage.skmt.ExecQuery2("select * FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_RECALCULO <> ? OR PE_RECALCULO <> ? OR PE_RECALCULO IS NOT NULL",Array As String("","null"))
'			LogColor(s3.RowCount,Colors.Yellow)
			If s3.RowCount > 0 Then
				c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
				s=B4XPages.MainPage.skmt.ExecQuery2("select iFNULL(sum(pe_costo_tot),0) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and (PE_RECALCULO = ? or PE_RECALCULO = ? or PE_RECALCULO IS NULL)",Array As String("","null"))
				s.Position=0
				Private s5 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select iFNULL(sum(PE_RECALCULOTOT),0) as TOTAL_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and (PE_RECALCULO <> ? or PE_RECALCULO <> ? OR PE_RECALCULO IS NOT NULL)",Array As String("","null"))
				s5.Position = 0
				If c.RowCount > 0 Then
					c.Position = 0
					If s.GetString("TOTAL_CLIE") = Null Then
						l_total.Text = 0
					Else
						l_total.Text =NumberFormat2((s.GetString("TOTAL_CLIE") + s5.GetString("TOTAL_CLIE")),0,2,2,False)
					End If
					total_cliente = s.GetString("TOTAL_CLIE") + s5.GetString("TOTAL_CLIE")
				End If
			Else
				c=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO,IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
				s=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
				s.Position=0
				If c.RowCount > 0 Then
					c.Position=0
					If s.GetString("TOTAL_CLIE") = Null Then
						l_total.Text = 0
					Else
						l_total.Text =NumberFormat2(s.GetString("TOTAL_CLIE"),0,2,2,False)
					End If
					total_cliente = s.GetString("TOTAL_CLIE")
				End If
			End If
		End If
	End If

	Log("============================================================")
	Log("============================================================")
	Log("============================================================")
'	*********************************************************
	l_total.Text = Subs.calculaTotalConPromoXRango(Subs.traecliente)
'	*********************************************************

	SV_ENCUESTA.Visible = False
	P_gallina.Visible = False
	p_pregunta1.Visible = False
	p_camara.Visible = False
	Panel2.Visible = False
	p_comentario.Visible = False
	p_transparenteTicketImpreso.Visible = False
	p_encuesta.Visible = False
	pnlPlanLealtad.Visible = False
	Panel10.Visible = False
	p_transparentePDF.Visible = False
	CH_FACTURA.Checked = False
	Dim fac As Cursor=B4XPages.MainPage.skmt.ExecQuery("Select ifnull(SUM(PE_COSTO_TOT), 0)  As TOTAL_CLIE, SUM(PE_CANT)  As CANT_CLIE, PC_FACTURA FROM PEDIDO_CLIENTE INNER JOIN PEDIDO ON PEDIDO_CLIENTE.PC_CLIENTE = PEDIDO.PE_CLIENTE WHERE (PE_CLIENTE IN (Select cuenta from cuentaa))")
	fac.Position = 0
	Private factura As String = 0
	If fac.GetString("PC_FACTURA") <> Null And IsNumber(fac.GetString("PC_FACTURA")) Then factura = fac.GetString("PC_FACTURA")
	If factura = "1" Then CH_FACTURA.Checked = True

'	If l_credito.IsInitialized Then
		c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO, CAT_CL_LIMITECREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position = 0
	If c.GetInt("CAT_CL_BCREDITO") = 1 Then

		Dim pagarepen As Cursor = B4XPages.MainPage.skmt.ExecQuery("select FECHA, SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		If pagarepen.RowCount > 0 Then
			pagarepen.Position = 0
			DateTime.DateFormat="dd/MM/yyyy"
			Dim FechaInicio As String = pagarepen.GetString("FECHA")  ' Formato: dd/MM/yyyy
'		Dim FechaHoy As String = DateTime.Date(DateTime.Now)  ' Fecha actual en formato dd/MM/yyyy
			Log(pagarepen.GetString("FECHA"))
			' Convertir las fechas a milisegundos (desde 01/01/1970)
			Dim TicksInicio As Long = DateTime.DateParse(FechaInicio)
			Dim TicksHoy As Long = DateTime.DateParse(DateTime.Date(DateTime.Now))

			' Calcular diferencia en días
			Dim DiferenciaDias As Int = (TicksHoy - TicksInicio) / DateTime.TicksPerDay

			' Mostrar resultado
			Log($"Días transcurridos: ${DiferenciaDias}"$)

			Dim c4 As Cursor=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_DIASCREDITO,0) AS CAT_CL_DIASCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
			c4.Position = 0

			If DiferenciaDias <= c4.GetInt("CAT_CL_DIASCREDITO") + 1 Then
				l_credito.Color = Colors.Green
				l_limite.Color = Colors.Green
			Else If DiferenciaDias > c4.GetInt("CAT_CL_DIASCREDITO") + 1 Then
				l_credito.Color = Colors.Red
				l_limite.Color = Colors.Red
			End If
		Else
			l_credito.Color = Colors.Transparent
			l_limite.Color = Colors.Transparent
		End If
			l_credito.Visible = True
			l_limite.Visible = True
			l_limite.Text = c.GetInt("CAT_CL_LIMITECREDITO")
		Else If c.GetInt("CAT_CL_BCREDITO") = 0 Then
			l_credito.Visible = False
			l_limite.Visible = False
		End If
'	End 

	Tels.Visible = False
	gest.Visible = False
	b_preventa2.Visible = False

	Dim coloressaldo As Cursor=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_CLASIFICADOR3,0) AS CAT_CL_CLASIFICADOR3, IFNULL(CAT_CL_CLASIFICADOR4,0) AS CAT_CL_CLASIFICADOR4, IFNULL(CAT_CL_CLASIFICADOR2,'') AS CAT_CL_CLASIFICADOR2 from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	coloressaldo.Position = 0 
	la_saldooper.Text = NumberFormat2(coloressaldo.GetDouble("CAT_CL_CLASIFICADOR3"),0,0,0,False)
	l_cajetillas.Text = NumberFormat2(coloressaldo.GetDouble("CAT_CL_CLASIFICADOR4"),0,0,0,False)
	l_animal.Text = coloressaldo.GetString("CAT_CL_CLASIFICADOR2")
	If coloressaldo.GetString("CAT_CL_CLASIFICADOR2") = "Chimpancé KIN" Then
		l_animal.Color = Colors.RGB(84,255,172)
		Label22.Color = Colors.RGB(84,255,172)
	Else If coloressaldo.GetString("CAT_CL_CLASIFICADOR2") = "Delfín Niky" Then
		l_animal.Color = Colors.RGB(84,255,245)
		Label22.Color = Colors.RGB(84,255,245)
	Else If coloressaldo.GetString("CAT_CL_CLASIFICADOR2") = "Tortuga KOPI" Then
		l_animal.Color = Colors.RGB(255,123,84)
		Label22.Color = Colors.RGB(255,123,84)
	Else If coloressaldo.GetString("CAT_CL_CLASIFICADOR2") = "Lechuza MON" Then
		l_animal.Color = Colors.RGB(255,250,140)
		Label22.Color = Colors.RGB(255,250,140)
	Else
		l_animal.Color = Colors.Transparent
		Label22.Color = Colors.Transparent
	End If
	
'	t1.Initialize("T1", 10000) ' 1000 = 1 second
'	t1.Enabled = True
End Sub

Sub MejorarPrecisionGPS As ResumableSub
'	If g.IsInitialized Then
'		g.Stop
'		Sleep(500)
'	End If
'
'	g.Initialize("GPS")
'	g.Start(0, 0) ' Máxima frecuencia
	CallSubDelayed(Tracker, "StartFLP2")
	' Esperar hasta 10 segundos por mejor precisión
	For i = 1 To 10
		Sleep(1000)
		If Tracker.FLP.GetLastKnownLocation.IsInitialized Then
			Dim loc As Location = Tracker.FLP.GetLastKnownLocation
			If loc.Accuracy < 25 Then ' Buena precisión
				Return True
			End If
		End If
	Next
	Return False ' No se logró buena precisión
End Sub

' Recalcula y pone en PEDIDO si el producto cumple lascondiciones para tener descuento
Sub recalculoXcant
'	Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT* FROM PEDIDO JOIN CAT_PROMOS_DESCUENTOS ON CAT_PD_PRODUCTO = PE_PROID WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_CEDIS = ? AND PE_CANT >= CAT_PD_RANGO AND CAT_PD_RANGO2 <= PE_CANT", Array As String(Subs.traeAlmacen))
	Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_CEDIS = ? AND PE_DESC = '0' ", Array As String(Subs.traeAlmacen))
	If c.RowCount > 0 Then
		For promespdes = 0 To c.RowCount -1
			c.Position = promespdes
			Dim rangosel As Cursor= B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO = ? AND CAT_PD_RANGO <= ? AND CAT_PD_RANGO2 >= ?",Array As String(c.GetString("PE_PROID"),c.GetInt("PE_CANT"),c.GetInt("PE_CANT")))
			If rangosel.RowCount > 0 Then
				For hjh = 0 To rangosel.RowCount-1
					rangosel.Position = hjh
					If rangosel.GetString("CAT_PD_TIER").Contains(Subs.traeTipoCliente) Then
						Log(c.GetString("PE_COSTOU"))
						Log(rangosel.GetString("CAT_PD_DESCUENTO"))
						Private recalculo As Float = c.GetString("PE_COSTOU") - NumberFormat2(((c.GetString("PE_COSTOU") * rangosel.GetString("CAT_PD_DESCUENTO"))/100),0,2,2,False)
						LogColor(recalculo,Colors.Blue)
						Log(c.GetString("PE_COSTOU"))
						Log(NumberFormat2(((c.GetString("PE_COSTOU") * rangosel.GetString("CAT_PD_DESCUENTO"))/100),0,2,2,False))
						Log(rangosel.GetString("CAT_PD_DESCUENTO"))
						Private recalculototal As Float =c.GetString("PE_CANT") * recalculo
						skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = ?, PE_RECALCULOTOT = ?, PE_RECCEDIS = ?, PE_RECCANT = PE_CANT WHERE PE_PROID = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND PE_CEDIS = ? and PE_FOLIO = ? AND IFNULL(PE_DESC,0) = 0",Array As String(NumberFormat2(recalculo,0,2,2,False) ,NumberFormat2(recalculototal,0,2,2,False),  rangosel.GetString("CAT_PD_COD_PROMO"),c.GetString("PE_PROID"), Subs.traeAlmacen, c.GetString("PE_FOLIO")))
					End If
				Next
			Else ' No cumple el rango ...
				Dim rangosel2 As Cursor= B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO = ? and ? > cat_pd_rango2",Array As String(c.GetString("PE_PROID"),c.GetInt("PE_CANT")))
'				definir rango sup y cantidad
				If rangosel2.RowCount > 0 Then
'					rangosel2.Position = 0
					For hjh = 0 To rangosel2.RowCount-1
						rangosel2.Position = hjh
						If rangosel2.GetString("CAT_PD_TIER").Contains(Subs.traeTipoCliente) Then
							Log(c.GetString("PE_COSTOU"))
							Log(rangosel2.GetString("CAT_PD_DESCUENTO"))
							Private recalculo As Float = c.GetString("PE_COSTOU") - NumberFormat2(((c.GetString("PE_COSTOU") * rangosel2.GetString("CAT_PD_DESCUENTO"))/100),0,2,2,False)
							LogColor(recalculo,Colors.Blue)
							Log(c.GetString("PE_COSTOU"))
							Log(NumberFormat2(((c.GetString("PE_COSTOU") * rangosel2.GetString("CAT_PD_DESCUENTO"))/100),0,2,2,False))
							Log(rangosel2.GetString("CAT_PD_DESCUENTO"))
							Private recalculototal As Float = rangosel2.GetString("CAT_PD_RANGO2") * recalculo
'							Restar total cantidad menos rango mayor para obtener la diferencia y saber cuanto hay de mas
'							INSERT de producto (diferencia entre el rango sup y cantidad de pedido
							skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = ?, PE_RECALCULOTOT = ?, PE_RECCEDIS = ?, PE_RECCANT = ? WHERE PE_PROID = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND PE_CEDIS = ? AND PE_FOLIO = ?",Array As String(NumberFormat2(recalculo,0,2,2,False),NumberFormat2(recalculototal,0,2,2,False),rangosel2.GetString("CAT_PD_COD_PROMO"), rangosel2.GetString("CAT_PD_RANGO2"),c.GetString("PE_PROID"),Subs.traeAlmacen, c.GetString("PE_FOLIO")))
						End If
					Next
				Else
					skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = NULL, PE_RECALCULOTOT = NULL, PE_RECCEDIS = NULL, PE_RECCANT = NULL WHERE PE_PROID = ? AND PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND PE_CEDIS = ? AND PE_FOLIO = ? AND IFNULL(PE_DESC,0) = 0",Array As String(c.GetString("PE_PROID"), Subs.traeAlmacen, c.GetString("PE_FOLIO")))
				End If
				rangosel2.Close
			End If
			rangosel.Close
		Next
	End If
	
	Private c As Cursor = B4XPages.MainPage.skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA FROM CUENTAA) AND PE_CEDIS = ? AND PE_DESC = '1' ", Array As String(Subs.traeAlmacen))
	If c.RowCount > 0 Then
		skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = NULL, PE_RECALCULOTOT = NULL, PE_RECCEDIS = NULL, PE_RECCANT = NULL WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND PE_CEDIS = ? AND PE_DESC = '1'",Array As String(Subs.traeAlmacen))
	End If
	skmt.ExecNonQuery2("UPDATE PEDIDO set PE_RECALCULO = NULL, PE_RECALCULOTOT = NULL, PE_RECCEDIS = NULL, PE_RECCANT = NULL WHERE PE_CLIENTE IN (SELECT CUENTA FROM CUENTAA) AND PE_CEDIS <> ?",Array As String(Subs.traeAlmacen))
End Sub

Private Sub LA_GPS_Click
	' Cuando el usuario toca el label de GPS
	MejorarPrecisionGPS
	
	ToastMessageShow("Mejorando precisión GPS...", False)
End Sub

'Sub t1_tick
'	MejorarPrecisionGPS
'	t1.Enabled = True
'End Sub

' En lugar de 100m y 50m, usar valores más amplios temporalmente
Private Sub RevisarGeocerca
'	Dim distanciaAlmacen As Int = distancealm ' Tu cálculo actual
'	Dim distanciaCliente As Int = distance ' Tu cálculo al cliente
	Log(distancealm)
	Log(distance)
	' Usar umbrales más amplios (ej: 150m y 80m)
	If distancealm > 0  Or distance > 50 Then
		If distancealm < 100 Or distance < 50 Then
			HabilitarBotones(True)
		Else
			HabilitarBotones(True)
		End If
	End If
End Sub

Sub HabilitarBotones(dentroDeRango As Boolean)
	If dentroDeRango Then
		If Tels.IsInitialized Then
			Tels.Visible = True
			gest.Visible = True
			Tels.Enabled = True
			gest.Enabled = True
			Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
			If future.RowCount > 0 Then
				future.Position = 0
				If future.GetInt("CAT_VA_VALOR") = 1 Then
					b_preventa2.Visible = True
					b_preventa2.Enabled = True
				Else If future.GetInt("CAT_VA_VALOR") = 0 Then
					b_preventa2.Enabled = False
					b_preventa2.Visible = False
				End If
			End If
'			ToastMessageShow("DENTRO de rango GPS - Botones habilitados", False)
		End If
	Else
		If Tels.IsInitialized Then
			b_preventa2.Visible = False
			Tels.Visible = False
			gest.Visible = False
'			ToastMessageShow("FUERA de rango GPS - Botones deshabilitados", False)
		End If
	End If
End Sub

Sub InicializarLocalizacionMejorada
	' Usar tanto GPS como red para mejor precisión
	Dim LocationManager As JavaObject
	LocationManager.InitializeStatic("android.location.LocationManager")
	' Solicitar ubicaciones de GPS y red
	g.Start(0, 0) ' GPS
	' También podrías usar la ubicación por red para casos interiores
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	LogColor($"Entrando a Cliente.GPS_LocationChanged"$, Colors.red)
'	Log($"${Location1.Latitude}, ${Location1.Longitude}"$)
	
	If Location1 = location2 Then
		contIguales = contIguales + 1
		Log("Coords Iguales")
		If contIguales >= 3 Then
'			contIguales = 0
'			Log("No hacemos nada")
			CallSubDelayed(Tracker, "StopFLP")
			Return
		End If
	Else
		contIguales = 0
	End If
	Log("################################################################################")
	Log("################################################################################")
	Log("################################################################################")
	location2 = Location1
'	Log(Location1.Latitude& " aqui guerra    "& Location1.Longitude)
'	If Tracker.FLP.GetLastKnownLocation.IsInitialized And Tracker.FLP.GetLastKnownLocation.Latitude <> 0 Then
'		B4XPages.MainPage.lat_gps = Tracker.FLP.GetLastKnownLocation.Latitude
'		B4XPages.MainPage.lon_gps = Tracker.FLP.GetLastKnownLocation.Longitude
''		Log("Coords set to: " & B4XPages.MainPage.lat_gps & " and " & B4XPages.MainPage.lon_gps)
'	End If
'	Log(m_lat &"   " & m_lon)

	' Si la precisión es mala, intentar mejorarla
	If Location1.Accuracy > 50 Then ' Mayor a 50 metros de error
		MejorarPrecisionGPS
		Return ' Esperar siguiente lectura
	End If

	' Filtrar ubicaciones con baja precisión
	If Location1.Accuracy > 50 Then ' Si la precisión es mayor a 50 metros, descartar
		Return
	End If

	' Usar promedio de varias lecturas
	Dim ultimasUbicaciones As List
	If ultimasUbicaciones.IsInitialized = False Then
		ultimasUbicaciones.Initialize
	End If

	ultimasUbicaciones.Add(Location1)
	If ultimasUbicaciones.Size > 5 Then
		ultimasUbicaciones.RemoveAt(0)
	End If

	' Calcular promedio
	Dim latPromedio, lonPromedio As Double
	For Each loc As Location In ultimasUbicaciones
		Log("***")
		latPromedio = latPromedio + loc.Latitude
		lonPromedio = lonPromedio + loc.Longitude
	Next
	latPromedio = latPromedio / ultimasUbicaciones.Size
	lonPromedio = lonPromedio / ultimasUbicaciones.Size

	' Usar ubicación promediada
	B4XPages.MainPage.lat_gps = latPromedio
	B4XPages.MainPage.lon_gps = lonPromedio
	
	If Tels.IsInitialized Then
		Dim al_longitud As String = 0 
		Dim al_latitud As String = 0
		c = skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?",Array As String("LATITUD"))
		If c.RowCount > 0 Then
			c.Position = 0
			Dim al_latitud As String = c.GetString("CAT_VA_VALOR")
		End If
		c.Close
		c = skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?",Array As String("LONGITUD"))
		If c.RowCount > 0 Then
			c.Position = 0
			Dim al_longitud As String = c.GetString("CAT_VA_VALOR")
		End If
		c.Close
		Dim ubi1, ubi2 As Location
		ubi1.Initialize2(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)
		ubi2.Initialize2(al_latitud, al_longitud)
		distancealm = ubi1.DistanceTo(ubi2)
	End If
	' Mostrar la precisión actual
	If LA_GPS.IsInitialized Then
		LA_GPS.Text = $"UBICACIÓN - Precisión: ${NumberFormat2(Location1.Accuracy, 0, 1, 1, False)}m"$
	End If
	' Solo usar ubicaciones con buena precisión
	If Location1.Accuracy < 30 Then ' Menos de 30 metros de error
		' Tu lógica actual aquí
		B4XPages.MainPage.lat_gps = Location1.Latitude
		B4XPages.MainPage.lon_gps = Location1.Longitude

		If m_lat.Length > 0 And B4XPages.MainPage.lat_gps <> "0" Then
			Dim l1, l2 As Location
			l1.Initialize2(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps)
'	Log($"Coordenadas de la tienda - lat:${m_lat}, lon:${m_lon}"$)
			l2.Initialize2(m_lat, m_lon)
			BT_QR.Enabled = True
'			LA_GPS.TextColor = Colors.Blue
'			LA_GPS.Text = "CON UBICACION GPS"
			B_GPS.Enabled = True
			'now we need the distance between our location and the target location
			Dim distance As Long
			distance = l1.DistanceTo(l2)  'the result is in meter
			c = skmt.ExecQuery("SELECT HABILITADO FROM GPS")
			If c.RowCount > 0 Then
				c.Position = 0
				Dim habi As String = c.GetString("HABILITADO")
			End If
			c.Close
			c = skmt.ExecQuery("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = 'GEOCERCA'")
			If c.RowCount > 0 Then
				c.Position = 0
				Dim geo As String = c.GetString("CAT_VA_VALOR")
			End If
			c.Close
			If gest.IsInitialized And Tels.IsInitialized Then
				If geo = "0" Then
					gest.Visible = True
					Tels.Visible = True
					Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
					If future.RowCount > 0 Then
						future.Position = 0
						If future.GetInt("CAT_VA_VALOR") = 1 Then
							b_preventa2.Visible = True
						Else If future.GetInt("CAT_VA_VALOR") = 0 Then
							b_preventa2.Visible = False
						End If
					End If
					iniciofin
'				b_geo = "0"
					bitacora.banderaGeoCerca = "0"
				Else If geo = "1" Then
					b_preventa2.Visible = False
					gest.Visible = False
					Tels.Visible = False
'				p_transparenteInicioFin.Visible = False
'				Log(999)
'				b_Inicio_Fin_venta.Visible = False
				End If
			End If
			If geo = "1" Then
				If distance < 1000000000000000000000 Then
					LA_GEO.TextColor = Colors.Blue
					Tels.Visible = True
					gest.Visible = True
					Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
					If future.RowCount > 0 Then
						future.Position = 0
						If future.GetInt("CAT_VA_VALOR") = 1 Then
							b_preventa2.Visible = True
						Else If future.GetInt("CAT_VA_VALOR") = 0 Then
							b_preventa2.Visible = False
						End If
					End If
					bitacora.inicioFin
					precision = "1"
'				b_geo = "0"
					bitacora.banderaGeoCerca = "0"
'				ToastMessageShow("DENTRO de rango GPS", False)
				Else If habi = "1" Then
					If distancealm < 50 Then
						precision = "0"
						LA_GEO.TextColor = Colors.Blue
						Tels.Visible = True
						gest.Visible = True
						Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
						If future.RowCount > 0 Then
							future.Position = 0
							If future.GetInt("CAT_VA_VALOR") = 1 Then
								b_preventa2.Visible = True
							Else If future.GetInt("CAT_VA_VALOR") = 0 Then
								b_preventa2.Visible = False
							End If
						End If
'					b_geo = "1"
						bitacora.banderaGeoCerca = "1"
						iniciofin
'					ToastMessageShow("DENTRO de rango GPS", False)
					Else If distancealm > 50 Then
						Tels.Visible = False
						gest.Visible = False
						b_preventa2.Visible = False
'					p_transparenteInicioFin.Visible = False
						Log(998)
'					b_Inicio_Fin_venta.Visible = False
						c = skmt.ExecQuery("SELECT PC_CLIENTE FROM PEDIDO_CLIENTE WHERE PC_CLIENTE IN (Select CUENTA from cuentaa)")
						If c.RowCount > 0 Then
							precision = "0"
							Tels.Visible = True
							gest.Visible = True
							Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
							If future.RowCount > 0 Then
								future.Position = 0
								If future.GetInt("CAT_VA_VALOR") = 1 Then
									b_preventa2.Visible = True
								Else If future.GetInt("CAT_VA_VALOR") = 0 Then
									b_preventa2.Visible = False
								End If
							End If
'						b_geo = "0"
							bitacora.banderaGeoCerca = "0"
							iniciofin
						Else If c.RowCount = 0 Then
							Private c5 As Cursor = skmt.ExecQuery("SELECT NV_CLIENTE FROM NOVENTA CLIENTE WHERE NV_CLIENTE IN (Select CUENTA from cuentaa)")
							If c5.RowCount > 0 Then
								Tels.Visible = True
								gest.Visible = True
								Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
								If future.RowCount > 0 Then
									future.Position = 0
									If future.GetInt("CAT_VA_VALOR") = 1 Then
										b_preventa2.Visible = True
									Else If future.GetInt("CAT_VA_VALOR") = 0 Then
										b_preventa2.Visible = False
									End If
								End If
								precision = "0"
'							b_geo = "0"
								iniciofin
							Else If c5.RowCount = 0 Then
								Tels.Visible = False
								gest.Visible = False
'							p_transparenteInicioFin.Visible = False
								Log(997)
'							b_Inicio_Fin_venta.Visible = False
								LA_GEO.TextColor = Colors.Red
								If ALMACEN = "1" Then
									Tels.Visible = False
									gest.Visible = True
									b_preventa2.Visible = False
'								b_geo = "0"
									bitacora.banderaGeoCerca = "0"
									iniciofin
								End If
							End If
							c5.Close
						End If
						c.Close
						LA_GEO.TextColor = Colors.Red
						If ALMACEN = "1" Then
							Tels.Visible = False
							gest.Visible = True
'						b_geo = "0"
							bitacora.banderaGeoCerca = "0"
							iniciofin
						End If
					End If
				Else If habi = 0 Then
					c = skmt.ExecQuery("SELECT PC_CLIENTE  FROM PEDIDO_CLIENTE WHERE PC_CLIENTE IN (Select CUENTA from cuentaa)")
					If c.RowCount > 0 Then
						Tels.Visible = True
						gest.Visible = True
						Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
						If future.RowCount > 0 Then
							future.Position = 0
							If future.GetInt("CAT_VA_VALOR") = 1 Then
								b_preventa2.Visible = True
							Else If future.GetInt("CAT_VA_VALOR") = 0 Then
								b_preventa2.Visible = False
							End If
						End If
'					b_geo = "0"
						bitacora.banderaGeoCerca = "0"
						iniciofin
					Else If c.RowCount = 0 Then
						b_preventa2.Visible = False
						Tels.Visible = False
						gest.Visible = False
'					p_transparenteInicioFin.Visible  = False
						Log(996)
'					b_Inicio_Fin_venta.Visible = False
						c2 = skmt.ExecQuery("SELECT NV_CLIENTE FROM NOVENTA CLIENTE WHERE NV_CLIENTE IN (Select CUENTA from cuentaa)")
						If c2.RowCount > 0 Then
							Tels.Visible = True
							gest.Visible = True
							Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
							If future.RowCount > 0 Then
								future.Position = 0
								If future.GetInt("CAT_VA_VALOR") = 1 Then
									b_preventa2.Visible = True
								Else If future.GetInt("CAT_VA_VALOR") = 0 Then
									b_preventa2.Visible = False
								End If
							End If
'						b_geo = "0"
							bitacora.banderaGeoCerca = "0"
							iniciofin
						Else If c2.RowCount = 0 Then
							b_preventa2.Visible = False
							Tels.Visible = False
							gest.Visible = False
'						p_transparenteInicioFin.Visible = False
							Log(995)
'						b_Inicio_Fin_venta.Visible = False
							LA_GEO.TextColor = Colors.Red
							If ALMACEN = "1" Then
								b_preventa2.Visible = False
								Tels.Visible = False
								gest.Visible = True
'							b_geo = "0"
								bitacora.banderaGeoCerca = "0"
								iniciofin
							End If
						End If
						c2.Close
						LA_GEO.TextColor = Colors.Red
						If ALMACEN = "1" Then
							Tels.Visible = False
							b_preventa2.Visible = False
							gest.Visible = True
'						b_geo = "0"
							bitacora.banderaGeoCerca = "0"
							iniciofin
						End If
					End If
					c.Close
				Else
					b_preventa2.Visible = False
					Tels.Visible = False
					gest.Visible = False
'				p_transparenteInicioFin.Visible = False
					Log(994)
'				b_Inicio_Fin_venta.Visible = False
					LA_GEO.TextColor = Colors.Red
					If ALMACEN = "1" Then
						Tels.Visible = False
						b_preventa2.Visible = False
						gest.Visible = True
'					b_geo = "0"
						bitacora.banderaGeoCerca = "0"
						iniciofin
					End If
				End If
			End If
		End If
'		RevisarGeocerca
	Else
		If LA_GPS.IsInitialized Then
'			LA_GPS.Text = $"UBICACIÓN - Precisión: ${NumberFormat2(Location1.Accuracy, 0, 1, 1, False)}m"$
			LA_GPS.Text = $"BAJA PRECISIÓN (${NumberFormat2(Location1.Accuracy, 0, 1, 1, False)}m)"$
			LA_GPS.TextColor = Colors.Red
		End If
	End If

	If cuenta.StartsWith("N") Then
		precision = "0"
		LA_GEO.TextColor = Colors.Blue
		Tels.Visible = True
		gest.Visible = True
		Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
		If future.RowCount > 0 Then
			future.Position = 0
			If future.GetInt("CAT_VA_VALOR") = 1 Then
				b_preventa2.Visible = False
			Else If future.GetInt("CAT_VA_VALOR") = 0 Then
				b_preventa2.Visible = False
			End If
		End If
'					b_geo = "1"
		bitacora.banderaGeoCerca = "1"
		iniciofin
'		ToastMessageShow("DENTRO de rango GPS", False)
	End If
'	19.4846431, -99.1458691 -> Keymon

	If LA_GEO.IsInitialized Then LA_GEO.Text= $"$1.2{distance/1000} kms"$

'	If distance > 100 Then ToastMessageShow("Fuera de rango GPS", False)
	B4XPages.MainPage.skmt.ExecNonQuery("DELETE FROM HIST_GPS")
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  HIST_GPS (HGDATE, HGLAT, HGLON) VALUES(?,?,?) ", Array As Object (sDate & sTime, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
'	CallSubDelayed(Tracker, "CreateLocationRequestSmallD")
End Sub

Private Sub p_pideGeoPass_Click

End Sub

'Muestra u oculta el boton de inicio y fin de venta
Private Sub iniciofin
'	If  Starter.enVenta = False Then
'		p_transparenteInicioFin.BringToFront
'		p_transparenteInicioFin.Visible = True
'		b_Inicio_Fin_venta.Visible = True
''		Log("Hacemos visible el boton de Inicio Venta")
'	Else
'		If b_Inicio_Fin_venta.Text <> "TERMINAR VENTA" Then
'			p_transparenteInicioFin.Visible = False
'			b_Inicio_Fin_venta.Visible = False
'		End If
'	End If
End Sub

Private Sub b_geopass_Click
	If et_geopass.Text.trim = "KMTS1" Then
		m_lat = B4XPages.MainPage.lat_gps
		m_lon = B4XPages.MainPage.lon_gps
		GPS_LocationChanged(Starter.ubicacionActual)
		skmt.ExecNonQuery($"update kmt_info3 set CAT_CL_LAT = '${B4XPages.MainPage.lat_gps}', CAT_CL_LONG = '${B4XPages.MainPage.lon_gps}' where CAT_CL_CODIGO = '${Subs.traeCliente}'"$)
		et_geopass.Text = ""
	Else
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_geoPass_GUNA"
		cmd.Parameters = Array As Object(et_geopass.Text.Trim, Subs.traeAlmacen, Subs.traeRuta)
		reqManager.ExecuteQuery(cmd , 0, "traeGeoPass")
		Log($"${Starter.server}, ${et_geopass.Text}, ${Subs.traeAlmacen}, ${Subs.traeRuta}"$)
		et_geopass.Text = ""
	End If
	p_pideGeoPass.Visible = False
'	ime.HideKeyboard
'	Log("Guardamos coords")
'	LATITUD = Starter.lat_gps
'	LONGITUD = Starter.lon_gps
'	GPS_LocationChanged(Starter.ubicacionActual)
'	Starter.skmt.ExecNonQuery($b_geopass"update kmt_info3 set CAT_CL_LAT = '${Starter.lat_gps}', CAT_CL_LONG = '${Starter.lon_gps}' where CAT_CL_CODIGO = '${Subs.traeCliente}'"$)
End Sub

Private Sub LA_GEO_LongClick
'	If distance > 99 Then
'		p_pideGeoPass.BringToFront
'		p_pideGeoPass.Visible = True
'	End If
End Sub

Sub JobDone(Job As HttpJob)
	If Job.Success = False Then
'		ToastMessageShow("Error: " & Job.ErrorMessage, True)
		LogColor("Error: " & Job.tag & " : " & Subs.parseHTTPError(Job.ErrorMessage), Colors.red)
'		LogColor("Error: " & Job.ErrorMessage, Colors.red)
	Else
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211110
		If Job.JobName = "DBRequest" Then
			Dim result1 As DBResult = reqManager.HandleJob(Job)
			If result1.Tag = "traeGeoPass" Then 'query tag
				Log("SIN REGISTROS " & result1.Rows.Size)
				If result1.Rows.Size = 0 Then MsgboxAsync("Contraseña equivocada, por favor intente de nuevo.", "ATENCION")
				For Each records() As Object In result1.Rows
					For Each k As String In result1.Columns.Keys
						Log(k & ": " & records(result1.Columns.Get(k)))
					Next
					Private permiso_geoPass As String = "KO"
					Log($"|${result1.Columns.Get("'OK'")}|"$)
'					Log($"|${records(result1.Columns.Get("'OK'"))}|"$)
'					If result1.Columns.Get("'OK'") <> "null" And result1.Columns.Get("'OK'") <> Null Then
						permiso_geoPass = result1.Columns.Get("'OK'")
'					End If
					If permiso_geoPass = "OK" Then
						m_lat = B4XPages.MainPage.lat_gps
						m_lon = B4XPages.MainPage.lon_gps
						GPS_LocationChanged(Starter.ubicacionActual)
						skmt.ExecNonQuery($"update kmt_info3 set CAT_CL_LAT = '${B4XPages.MainPage.lat_gps}', CAT_CL_LONG = '${B4XPages.MainPage.lon_gps}' where CAT_CL_CODIGO = '${Subs.traeCliente}'"$)
						Dim cmd As DBCommand
						cmd.Initialize
						cmd.Name = "delete_geoPass_GUNA"
						cmd.Parameters = Array As Object( Subs.traeAlmacen, Subs.traeRuta)
						reqManager.ExecuteQuery(cmd , 0, "traeGeoPass")
					Else
						MsgboxAsync("Contraseña equivocada, por favor intente de nuevo.", "ATENCION")
					End If
				Next
			End If

			If result1.Tag = "codigoAutorizacion" Then
				If result1.Rows.Size > 0 Then
					Log("Si  hay codigo de autorizaion")
					For Each records() As Object In result1.Rows
						For Each k As String In result1.Columns.Keys
							Log(k & ": " & records(result1.Columns.Get(k)))
						Next
					Next
					Dim cmd As DBCommand
					cmd.Initialize
					cmd.Name = "delete_codigoAutorizacion"
					cmd.Parameters = Array As Object(et_codigoAutorizacion.Text.Trim, Subs.traeRuta, Subs.traeAlmacen)
					reqManager.ExecuteCommand(cmd , "deleteCodigoAutorizacion")
					DateTime.DateFormat = "YYYY/MM/dd HH:mm:ss"
					cmd.Initialize
					cmd.Name = "update_codigoAutorizacion"
'					Log($"(${DateTime.Date(DateTime.Now)}, ${Subs.traeUsuarioDeBD}, ${et_codigoAutorizacion.Text.Trim}, ${Subs.traeRuta}, ${Subs.traeAlmacen}"$)
					cmd.Parameters = Array As Object(DateTime.Date(DateTime.Now), Subs.traeUsuarioDeBD, et_codigoAutorizacion.Text.Trim, Subs.traeRuta, Subs.traeAlmacen)
					reqManager.ExecuteCommand(cmd , "updateCodigoAutorizacion")
					Starter.skmt.ExecNonQuery("delete from ticket_impreso where idCliente in (select cuenta from cuentaa)")
					p_transparenteTicketImpreso.Visible = False
					et_codigoAutorizacion.Text = ""
					teclado.HideKeyboard
					Starter.skmt.ExecNonQuery("Update kmt_info3 set CONFIRMADO = 0  WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
					Starter.skmt.ExecNonQuery("Update CODIGOS_CREDITO set BANDERA = 0  WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
					ToastMessageShow("Listo, ya se puede modificar la venta.", True)
				Else
					ToastMessageShow("El codigo es incorrecto, por favor revise y vuelva a intentar!!", True)
				End If
			End If
			If result1.Tag = "delete_codigoAutorizacion" Then
				Log("Codigo Borrado!!")
			End If
			If result1.Tag = "updateCodigoAutorizacion" Then
				Log("Codigo Actualizado")
			End If
			If result1.Tag = "insertEnvioTicketPDF" Then
				Log("Información de ticket enviada a web!!")
			End If
		End If

'		If Job.JobName = "DBRequest" Then
'			Dim result1 As DBResult = reqManager.HandleJob(Job)
'			If result1.Tag = "CHECAENCUESTA" Then 'query tag
'				Log("SIN REGISTROS " & result1.Rows.Size)
'			
'				For Each records() As Object In result1.Rows
'					Dim CUANTOSENCUESTA As String = records(result1.Columns.Get("CUANTOS"))
'					Log(CUANTOSENCUESTA)
'					If CUANTOSENCUESTA = "0" Then
'						cmd.Initialize
'						cmd.Name ="insert_drop_GV2_4"
'						cmd.Parameters = Array As Object(usuario,B4XPages.MainPage.principal.e_ruta.text,sDate,"",sTime,"","","","","ENCUESTA",ALMACEN,Application.VersionName,Starter.encuesta)
'						B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "inst_drop")
'					End If
'				Next
'			End If
'		End If

		If result1.Tag = "kmt_datos_foto" Then 'query tag
			For Each records() As Object In result1.Rows
				Dim CAT_CL_FOTO() As Byte = records(result1.Columns.Get("CAT_CL_FOTO"))
			Next
			Log("si paso")
			B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE kmt_info3 SET foto = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(CAT_CL_FOTO))
			
			Dim fotomostrar As Cursor = Starter.skmt.ExecQuery("SELECT foto FROM kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
			If fotomostrar.RowCount > 0 Then
				Dim fotomostrar1 As Cursor = Starter.skmt.ExecQuery("SELECT foto FROM kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA) AND foto IS NULL")
				If fotomostrar1.RowCount > 0 Then
					ImageView4.Bitmap = LoadBitmap(File.DirAssets,"images.png")
					Log("aqui no hay foto")
				Else
					fotomostrar.Position = 0
					Private fotomostrarfinal() As Byte = fotomostrar.GetBlob("foto")
					Dim InputStream1 As InputStream
					InputStream1.InitializeFromBytesArray(fotomostrarfinal, 0, fotomostrarfinal.Length)
					Dim Bitmap1 As Bitmap
					Bitmap1.Initialize2(InputStream1)
					InputStream1.Close
					ImageView4.Bitmap = Bitmap1
					Log("aqui si hay foto")
				End If
			End If
		End If
	End If
	Job.Release
End Sub

Sub ListView1_ItemLongClick (Position As Int, Value As Object)

End Sub

Sub gest_Click
	''	Mejorar precisión antes de procesar la venta
	''	MejorarPrecisionGPS
	''	Sleep(500) ' Esperar un poco para que el GPS se estabilice
	
	Dim checkenc As Cursor = B4XPages.MainPage.skmt.ExecQuery("select * FROM HIST_ENCUESTA_BAT WHERE CLIENTE In (Select cuenta from cuentaa)")
	If checkenc.RowCount = 0 Then
		Dim checkenc1 As Cursor = B4XPages.MainPage.skmt.ExecQuery("select * FROM ENCUESTAS_BAT WHERE CLIENTE In (Select cuenta from cuentaa)")
		If checkenc1.RowCount = 0 Then
			
			If ALMACEN = 81 Or ALMACEN = 94 Then
		
				Dim coloressaldo As Cursor=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_CLASIFICADOR5,0) AS CAT_CL_CLASIFICADOR5 from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
				If coloressaldo.RowCount > 0 Then
					coloressaldo.Position = 0
					If coloressaldo.GetString("CAT_CL_CLASIFICADOR5") = "1" Then
						scv_bat.Visible = True
						scv_bat.Panel.RemoveAllViews
						scv_bat.Panel.LoadLayout("encuesta_1")
						scv_bat.Panel.Height = p_encu.Height
						p_encu.Width = scv_bat.Width
		
		
						Dim itembat1 As List
						itembat1.Initialize
						itembat1.Add("Selecciona una opcion")
						itembat1.Add("Ninguno")
						itembat1.Add("Menos de medio paquete")
						itembat1.Add("Medio paquete a 1 paquete")
						itembat1.Add("1.1 a 2.9 paquetes")
						itembat1.Add("3 a 5.9 paquetes")
						itembat1.Add("6 a 10.9 paquetes")
						itembat1.Add("11 a 20.9 paquetes")
						itembat1.Add("21 a 30 paquetes")
						itembat1.Add("Más de 30 paquetes")
						cb_p1.SetItems(itembat1)
						e_1 = "Selecciona una opcion"
		
						Dim itembat2 As List
						itembat2.Initialize
						itembat2.Add("Selecciona una opcion")
						itembat2.Add("Ninguno")
						itembat2.Add("Menos de medio paquete")
						itembat2.Add("Medio paquete a 1 paquete")
						itembat2.Add("1.1 a 2.9 paquetes")
						itembat2.Add("3 a 5.9 paquetes")
						itembat2.Add("6 a 10.9 paquetes")
						itembat2.Add("11 a 20.9 paquetes")
						itembat2.Add("21 a 30 paquetes")
						itembat2.Add("Más de 30 paquetes")
						cb_p2.SetItems(itembat2)
						e_2 = "Selecciona una opcion"
		
						Dim itembat3 As List
						itembat3.Initialize
						itembat3.Add("Selecciona una opcion")
						itembat3.Add("Ninguno")
						itembat3.Add("Menos de medio paquete")
						itembat3.Add("Medio paquete a 1 paquete")
						itembat3.Add("1.1 a 2.9 paquetes")
						itembat3.Add("3 a 5.9 paquetes")
						itembat3.Add("6 a 10.9 paquetes")
						itembat3.Add("11 a 20.9 paquetes")
						itembat3.Add("21 a 30 paquetes")
						itembat3.Add("Más de 30 paquetes")
						cb_p3.SetItems(itembat3)
						e_3 = "Selecciona una opcion"
		
						Dim itembat4 As List
						itembat4.Initialize
						itembat4.Add("Selecciona una opcion")
						itembat4.Add("Ninguno")
						itembat4.Add("Menos de medio paquete")
						itembat4.Add("Medio paquete a 1 paquete")
						itembat4.Add("1.1 a 2.9 paquetes")
						itembat4.Add("3 a 5.9 paquetes")
						itembat4.Add("6 a 10.9 paquetes")
						itembat4.Add("11 a 20.9 paquetes")
						itembat4.Add("21 a 30 paquetes")
						itembat4.Add("Más de 30 paquetes")
						cb_p4.SetItems(itembat4)
						e_4 = "Selecciona una opcion"
		
						Dim itembat5 As List
						itembat5.Initialize
						itembat5.Add("Selecciona una opcion")
						itembat5.Add("Ninguno")
						itembat5.Add("Tiendatek")
						itembat5.Add("Yomp")
						itembat5.Add("Systienda")
						itembat5.Add("MyBusiness POS")
						itembat5.Add("Eleventa")
						itembat5.Add("Otro")
						cb_p5.SetItems(itembat5)
						e_5 = "Selecciona una opcion"
					Else If coloressaldo.GetString("CAT_CL_CLASIFICADOR5") = "5" Then
				
						scv_bat.Visible = True
						scv_bat.Panel.RemoveAllViews
						scv_bat.Panel.LoadLayout("encuesta_2")
						scv_bat.Panel.Height = p_encu.Height
						p_encu.Width = scv_bat.Width
		
		
						Dim itembat1 As List
						itembat1.Initialize
						itembat1.Add("Selecciona una opcion")
						itembat1.Add("Ninguno")
						itembat1.Add("Menos de medio cartón")
						itembat1.Add("Medio cartón a 1 cartón")
						itembat1.Add("1.1 a 3.9 cartones")
						itembat1.Add("4 a 5.9 cartones")
						itembat1.Add("6 a 10.9 cartones")
						itembat1.Add("11 a 20.9 cartones")
						itembat1.Add("21 a 30.9 cartones")
						itembat1.Add("31 a 40 cartones")
						itembat1.Add("Más de 40 cartones")
						cb_p1.SetItems(itembat1)
						e_1 = "Selecciona una opcion"
		
						Dim itembat2 As List
						itembat2.Initialize
						itembat2.Add("Selecciona una opcion")
						itembat2.Add("Ninguno")
						itembat2.Add("Menos de medio cartón")
						itembat2.Add("Medio cartón a 1 cartón")
						itembat2.Add("1.1 a 3.9 cartones")
						itembat2.Add("4 a 5.9 cartones")
						itembat2.Add("6 a 10.9 cartones")
						itembat2.Add("11 a 20.9 cartones")
						itembat2.Add("21 a 30.9 cartones")
						itembat2.Add("31 a 40 cartones")
						itembat2.Add("Más de 40 cartones")
						cb_p2.SetItems(itembat2)
						e_2 = "Selecciona una opcion"
		
						Dim itembat3 As List
						itembat3.Initialize
						itembat3.Add("Selecciona una opcion")
						itembat3.Add("Ninguno")
						itembat3.Add("Menos de medio cartón")
						itembat3.Add("Medio cartón a 1 cartón")
						itembat3.Add("1.1 a 3.9 cartones")
						itembat3.Add("4 a 5.9 cartones")
						itembat3.Add("6 a 10.9 cartones")
						itembat3.Add("11 a 20.9 cartones")
						itembat3.Add("21 a 30.9 cartones")
						itembat3.Add("31 a 40 cartones")
						itembat3.Add("Más de 40 cartones")
						cb_p3.SetItems(itembat3)
						e_3 = "Selecciona una opcion"
		
						Dim itembat4 As List
						itembat4.Initialize
						itembat4.Add("Selecciona una opcion")
						itembat4.Add("Ninguno")
						itembat4.Add("Menos de medio cartón")
						itembat4.Add("Medio cartón a 1 cartón")
						itembat4.Add("1.1 a 3.9 cartones")
						itembat4.Add("4 a 5.9 cartones")
						itembat4.Add("6 a 10.9 cartones")
						itembat4.Add("11 a 20.9 cartones")
						itembat4.Add("21 a 30.9 cartones")
						itembat4.Add("31 a 40 cartones")
						itembat4.Add("Más de 40 cartones")
						cb_p4.SetItems(itembat4)
						e_4 = "Selecciona una opcion"
		
						Dim itembat5 As List
						itembat5.Initialize
						itembat5.Add("Selecciona una opcion")
						itembat5.Add("Ninguno")
						itembat5.Add("Menos de medio cartón")
						itembat5.Add("Medio cartón a 1 cartón")
						itembat5.Add("1.1 a 3.9 cartones")
						itembat5.Add("4 a 5.9 cartones")
						itembat5.Add("6 a 10.9 cartones")
						itembat5.Add("11 a 20.9 cartones")
						itembat5.Add("21 a 30.9 cartones")
						itembat5.Add("31 a 40 cartones")
						itembat5.Add("Más de 40 cartones")
						cb_p5.SetItems(itembat5)
						e_5 = "Selecciona una opcion"
				
						Dim itembat6 As List
						itembat6.Initialize
						itembat6.Add("Selecciona una opcion")
						itembat6.Add("Ninguno")
						itembat6.Add("Menos de medio cartón")
						itembat6.Add("Medio cartón a 1 cartón")
						itembat6.Add("1.1 a 3.9 cartones")
						itembat6.Add("4 a 5.9 cartones")
						itembat6.Add("6 a 10.9 cartones")
						itembat6.Add("11 a 20.9 cartones")
						itembat6.Add("21 a 30.9 cartones")
						itembat6.Add("31 a 40 cartones")
						itembat6.Add("Más de 40 cartones")
						cb_p6.SetItems(itembat6)
						e_6 = "Selecciona una opcion"
				
						Dim itembat7 As List
						itembat7.Initialize
						itembat7.Add("Selecciona una opcion")
						itembat7.Add("Ninguno")
						itembat7.Add("Menos de medio cartón")
						itembat7.Add("Medio cartón a 1 cartón")
						itembat7.Add("1.1 a 3.9 cartones")
						itembat7.Add("4 a 5.9 cartones")
						itembat7.Add("6 a 10.9 cartones")
						itembat7.Add("11 a 20.9 cartones")
						itembat7.Add("21 a 30.9 cartones")
						itembat7.Add("31 a 40 cartones")
						itembat7.Add("Más de 40 cartones")
						cb_p7.SetItems(itembat7)
						e_7 = "Selecciona una opcion"
				
						Dim itembat8 As List
						itembat8.Initialize
						itembat8.Add("Selecciona una opcion")
						itembat8.Add("Ninguno")
						itembat8.Add("Menos de medio cartón")
						itembat8.Add("Medio cartón a 1 cartón")
						itembat8.Add("1.1 a 3.9 cartones")
						itembat8.Add("4 a 5.9 cartones")
						itembat8.Add("6 a 10.9 cartones")
						itembat8.Add("11 a 20.9 cartones")
						itembat8.Add("21 a 30.9 cartones")
						itembat8.Add("31 a 40 cartones")
						itembat8.Add("Más de 40 cartones")
						cb_p8.SetItems(itembat8)
						e_8 = "Selecciona una opcion"
				
						Dim itembat9 As List
						itembat9.Initialize
						itembat9.Add("Selecciona una opcion")
						itembat9.Add("Ninguno")
						itembat9.Add("Menos de medio cartón")
						itembat9.Add("Medio cartón a 1 cartón")
						itembat9.Add("1.1 a 3.9 cartones")
						itembat9.Add("4 a 5.9 cartones")
						itembat9.Add("6 a 10.9 cartones")
						itembat9.Add("11 a 20.9 cartones")
						itembat9.Add("21 a 30.9 cartones")
						itembat9.Add("31 a 40 cartones")
						itembat9.Add("Más de 40 cartones")
						cb_p9.SetItems(itembat9)
						e_9 = "Selecciona una opcion"
				
						Dim itembat10 As List
						itembat10.Initialize
						itembat10.Add("Selecciona una opcion")
						itembat10.Add("Ninguno")
						itembat10.Add("Menos de medio cartón")
						itembat10.Add("Medio cartón a 1 cartón")
						itembat10.Add("1.1 a 3.9 cartones")
						itembat10.Add("4 a 5.9 cartones")
						itembat10.Add("6 a 10.9 cartones")
						itembat10.Add("11 a 20.9 cartones")
						itembat10.Add("21 a 30.9 cartones")
						itembat10.Add("31 a 40 cartones")
						itembat10.Add("Más de 40 cartones")
						cb_p10.SetItems(itembat10)
						e_10 = "Selecciona una opcion"
					Else
						vent
					End If
				End If
			Else
				vent
			End If
			
		Else
			vent
		End If
	Else
		vent
	End If
	

End Sub

Sub vent
	
	Dim pagarepen As Cursor = B4XPages.MainPage.skmt.ExecQuery("select FECHA, SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If pagarepen.RowCount > 0 Then
		pagarepen.Position = 0
		DateTime.DateFormat="dd/MM/yyyy"
		Dim FechaInicio As String = pagarepen.GetString("FECHA")  ' Formato: dd/MM/yyyy
		'		Dim FechaHoy As String = DateTime.Date(DateTime.Now)  ' Fecha actual en formato dd/MM/yyyy
		Log(pagarepen.GetString("FECHA"))
	
		' Convertir las fechas a milisegundos (desde 01/01/1970)
		Dim TicksInicio As Long = DateTime.DateParse(FechaInicio)
		Dim TicksHoy As Long = DateTime.DateParse(DateTime.Date(DateTime.Now))
	
		' Calcular diferencia en días
		Dim DiferenciaDias As Int = (TicksHoy - TicksInicio) / DateTime.TicksPerDay
	
		' Mostrar resultado
		Log($"Días transcurridos: ${DiferenciaDias}"$)
	
		c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_DIASCREDITO,0) AS CAT_CL_DIASCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position = 0
	
		If ALMACEN = 81 Or ALMACEN = 94 Then
			If DiferenciaDias <= c.GetInt("CAT_CL_DIASCREDITO") + 8  Then
				'			MsgboxAsync($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Recordatorio")
				Msgbox2Async($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Recordatorio", "Ok", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
				Wait For Msgbox_Result (resultado As Int)
				If resultado = DialogResponse.POSITIVE Then
					gestionar
				End If
			Else If DiferenciaDias > c.GetInt("CAT_CL_DIASCREDITO") + 8 Then
				MsgboxAsync($"No se puede realizar venta por que presenta ${(DiferenciaDias-(c.GetInt("CAT_CL_DIASCREDITO") +1))} días de atraso en el credito, por un monto de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Atención")
			End If
		Else
			If DiferenciaDias <= c.GetInt("CAT_CL_DIASCREDITO") + 1  Then
				'			MsgboxAsync($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Recordatorio")
				Msgbox2Async($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Recordatorio", "Ok", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
				Wait For Msgbox_Result (resultado As Int)
				If resultado = DialogResponse.POSITIVE Then
					gestionar
				End If
			Else If DiferenciaDias > c.GetInt("CAT_CL_DIASCREDITO") + 8 Then
				MsgboxAsync($"No se puede realizar venta por que presenta ${(DiferenciaDias-(c.GetInt("CAT_CL_DIASCREDITO") +1))} días de atraso en el credito, por un monto de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Atención")
			End If
		End If
		
	Else
		gestionar
	End If
End Sub

Sub gestionar
	If B_IMP.Visible = True Then
		If Not(Subs.revisaImpreso) Then
			c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(encuesta,0) AS encuesta from kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
			c.Position = 0
			If c.GetString("encuesta") = "0" Then
				Dim Intent1 As Intent
				Dim enviorutas As String = "guna://tienda360/config?clienteId="&la_cuenta.Text&"&almacen="&ALMACEN&"&ruta="&Subs.traeRuta
				Log(enviorutas)
				Intent1.Initialize(Intent1.ACTION_VIEW, enviorutas)
				Try
					Starter.encuesta = 1
					Dim cmd As DBCommand
					skmt.ExecNonQuery2("UPDATE kmt_info3 SET encuesta = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(1))
					StartActivity(Intent1)
					compra
				Catch
					Starter.encuesta = 0
'					Dim cmd As DBCommand
'					skmt.ExecNonQuery2("UPDATE kmt_info3 SET encuesta = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(2))
'					ToastMessageShow("La aplicación Tienda 360 no está instalada o no puede manejar la URL.", True)
					compra
				End Try
'				cmd.Initialize
'				cmd.Name = "SELECT_TMP_DROP_ENCUESTA_GUNA"
'				cmd.Parameters = Array As Object(usuario, B4XPages.MainPage.principal.e_ruta.text, ALMACEN, "ENCUESTA")
'				B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "CHECAENCUESTA")
			Else
				compra
			End If
		Else
			If Subs.traeAlmacen = 94 Then
				c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(encuesta,0) AS encuesta from kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
				c.Position = 0
				If c.GetString("encuesta") = "0" Then
					Dim Intent1 As Intent
					Dim enviorutas As String = "guna://tienda360/config?clienteId="&la_cuenta.Text&"&almacen="&ALMACEN&"&ruta="&Subs.traeRuta
					Log(enviorutas)
					Intent1.Initialize(Intent1.ACTION_VIEW, enviorutas)
					Try
						Starter.encuesta = 1
						Dim cmd As DBCommand
						skmt.ExecNonQuery2("UPDATE kmt_info3 SET encuesta = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(1))
						StartActivity(Intent1)
						compra
					Catch
						Starter.encuesta = 0
'					Dim cmd As DBCommand
'					skmt.ExecNonQuery2("UPDATE kmt_info3 SET encuesta = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(2))
'					ToastMessageShow("La aplicación Tienda 360 no está instalada o no puede manejar la URL.", True)
						compra
					End Try
'				cmd.Initialize
'				cmd.Name = "SELECT_TMP_DROP_ENCUESTA_GUNA"
'				cmd.Parameters = Array As Object(usuario, B4XPages.MainPage.principal.e_ruta.text, ALMACEN, "ENCUESTA")
'				B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "CHECAENCUESTA")
				Else
					compra
				End If
			Else
				p_transparenteTicketImpreso.Visible = True
			End If
		End If
	Else
		c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(encuesta,0) AS encuesta from kmt_info3 where CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
		c.Position = 0
		If c.GetString("encuesta") = "0" Then
			Dim Intent1 As Intent
			Dim enviorutas As String = "guna://tienda360/config?clienteId="&la_cuenta.Text&"&almacen="&ALMACEN&"&ruta="&Subs.traeRuta
			Log(enviorutas)
			Intent1.Initialize(Intent1.ACTION_VIEW, enviorutas)
			Try
				Starter.encuesta = 1
				Dim cmd As DBCommand
				skmt.ExecNonQuery2("UPDATE kmt_info3 SET encuesta = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(1))
				StartActivity(Intent1)
				compra
			Catch
				Starter.encuesta = 0
'				Dim cmd As DBCommand
'				skmt.ExecNonQuery2("UPDATE kmt_info3 SET encuesta = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(2))
'				ToastMessageShow("La aplicación Tienda 360 no está instalada o no puede manejar la URL.", True)
				compra
			End Try
'			cmd.Initialize
'			cmd.Name = "SELECT_TMP_DROP_ENCUESTA_GUNA"
'			cmd.Parameters = Array As Object(usuario, B4XPages.MainPage.principal.e_ruta.text, ALMACEN, "ENCUESTA")
'			B4XPages.MainPage.reqManager.ExecuteQuery(cmd , 0, "CHECAENCUESTA")
		Else
			compra
		End If
	End If
End Sub

Sub compra
'	If ALMACEN = "4" Or ALMACEN = "36" Then
'	Log(Subs.traeAlmacen)

'	Almacenes 6 y 79 de SCAT y Norte 45.
'	En SCAT es ruta 3
'	Norte 45 (79) Rutas: 702, 703, 707, 718, 730, 732, 733, 734.

'	COACALCO- 35--
'	NORTE 45- 75--
'	ATIZAPAN- 56--
'	VALLEJO- 73--
'	IZTAPALAPA- 43--
'	CEDA- 54--
'	PACHUCA- 15--
	Private rutasEncuesta As List
	rutasEncuesta.Initialize2(Array As Int(702, 703, 707, 718, 730, 732, 733, 734))
	Private alamcenesEncuesta As List
	alamcenesEncuesta.Initialize2(Array As Int(15, 35, 43, 54, 56, 73, 75, 79))  ' Almacenes para la encuesta de Pedigree

'	ALMACEN = 79
'	LA_RUTA = 732
	' Or (ALMACEN = 79 And rutasEncuesta.IndexOf(LA_RUTA.As(Int)) > -1)

	' Encuesta Pedigree
'	If (alamcenesEncuesta.IndexOf(ALMACEN.As(Int)) > -1 ) Or (ALMACEN = 6 And LA_RUTA = 3) Then
'		Log($"${cuest.encuestaIniciada} - ${cuest.clienteConCuestionario(Subs.traeCliente)}"$)
'		If Not(cuest.encuestaIniciada) And Not(cuest.clienteConCuestionario(Subs.traeCliente)) Then
'			cuest.agregaPreguntaCheckbox("1", "¿Qué productos de Kileo Perro encuentras en esta tienda?", Array As String("Pedigree Adulto", "Pedigree Cachorro", "Pedigree Razas Pequeñas", "Champ", "PAL","DOG CHOW ADULTO","DOG CHOW CACHORRO","DOG CHOW RAZAS PEQUEÑAS","Campeon","Ganador","Poder canino","Perron","Silverkan","Woow","Chapetes","Dyno","Beriscan","Nogacan","Nutrescan","Fidus","Amigo Gourmet","Otros","Ninguno de los anteriores"))
'			Return False
'		End If
'	End If

	If TOMAR_FOTO = 0 Then
		Cuestionario
	Else
		Dim Items As List
		Items.Initialize
		Items.Add("Selecciona una opción")
		Items.Add("Tienda de Abarrotes (Abarrotes, Misceláneas, Minisupers, Particulares con Venta y Cremerías)")
		Items.Add("Recaudería (Frutas y Verduras)")
		Items.Add("Vinos y Licores")
		Items.Add("Carnicería o Pollería")
		Items.Add("Farmacia")
		Items.Add("Jarciería (Productos de Limpieza)")
		Items.Add("Papelería y Regalos")
		Items.Add("Tortillería")
		Items.Add("Escuelas")
		Items.Add("Estanquillos (Puestos Semifijos)")
		Items.Add("Fonda, Cocina Económica, Cafetería)")
		Items.Add("Tlapalería, Ferretería")
		Items.Add("Dulcería, Materias Primas")
		Items.Add("Semillas y Chiles Secos")
		Items.Add("Cybercafé")
		Items.Add("Hotel")
		Items.Add("Veterinaria")
		Items.Add("Tienda de Mascotas")
		Items.Add("Otros")
		cb_pregunta.SetItems(Items)
		girotienda = "Selecciona una opcion"
		c=skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM HIST_ENCUESTA_CLIENTE WHERE HEC_CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		CUENTA_MODULO = c.GetString("CUANTOS")
		c.Close
		If CUENTA_MODULO > 0 Then
			c=skmt.ExecQuery("SELECT HEC_MODULO FROM HIST_ENCUESTA_CLIENTE WHERE HEC_CLIENTE IN (Select CUENTA from cuentaa)")
			c.Position=0
			que_modulo = c.GetString("HEC_MODULO")
			c.Close
		End If
		Log(Subs.traeAlmacen)
		c=skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM ENCUESTA_MODULO1 WHERE CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		EXISTE = c.GetString("CUANTOS")
		c.Close
	
		c=skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM ENCUESTA_MODULO2 WHERE CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		EXISTE2 = c.GetString("CUANTOS")
		c.Close
	
		c=skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM ENCUESTA_MODULO3 WHERE CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		EXISTE3 = c.GetString("CUANTOS")
		c.Close
	
		c=skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM ENCUESTA_MODULO4 WHERE CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		EXISTE4 = c.GetString("CUANTOS")
		c.Close
	
		c=skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM ENCUESTA_MODULO5 WHERE CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		EXISTE5 = c.GetString("CUANTOS")
		c.Close
	
		' esto para la primera encuesta m1
'		p_cliente.Visible = False
'		SV_ENCUESTA.Visible = True
'		SV_ENCUESTA.Panel.LoadLayout("ENCUESTA")
'		Panel5.Width = Root.Width * 0.94
'		SV_ENCUESTA.Panel.Height = Panel5.Height + 60
'		Panel7.Visible = False
		'
'		' para la m2
'		p_cliente.Visible = False
'		SV_ENCUESTA.Visible = True
'		SV_ENCUESTA.Panel.LoadLayout("ESNCUESTA_m2")
'		Panel5.Width = Root.Width * 0.94
'		SV_ENCUESTA.Panel.Height = Panel5.Height + 60
'		Panel7_M2.Visible = False
'	
'		' para la m3
'		p_cliente.Visible = False
'		SV_ENCUESTA.Visible = True
'		SV_ENCUESTA.Panel.LoadLayout("ENCUESSTA_M3")
'		Panel5.Width = Root.Width * 0.94
'		SV_ENCUESTA.Panel.Height = Panel5.Height + 60

		If EXISTE = 0 And EXISTE2 = 0 And EXISTE3 = 0 And EXISTE4 = 0 And EXISTE5 = 0 Then
			S = skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("CUESTIONARIO"))
			S.Position = 0
			If s.GetString("CAT_VA_VALOR") > "0" Then
				''	If "3" > "0" Then
				ENCUESTA = s.GetString("CAT_VA_VALOR")
				ENCUESTA =  "3"
'				c=skmt.ExecQuery("SELECT COUNT(*) AS CUANTOS FROM HIST_ENCUESTA_PED_DIST_1 WHERE TIENDA IN (Select CUENTA from cuentaa)")
'				c.Position=0
'				EXISTE  = c.GetString("CUANTOS")
'				c.Close
'				If EXISTE = 0 Then
'					Dim result As Int= -3
'					Do While result=-3
'						result = 	Msgbox2("Entiendo, acepto y consiento que GUNA usará mis datos Personales y serán tratados acorde con lo establecido en la Ley Federal de Protección de Datos Personales en Posesión de los Particulares (en lo sucesivo la “Ley”), y su respectivo Reglamento; bajo lo manifestado en el Aviso de Privacidad – Texto Completo – que se encuentra en la página www.guna.com.mx", "AVISO DE PRIVACIDAD","ACEPTO","", "NO ACEPTO",LoadBitmap(File.DirAssets,"alert2.png"))
'						Select Case result
'							Case DialogResponse.POSITIVE
'								p_pregunta1.Visible = True
'							Case DialogResponse.NEGATIVE
'								''HIST_ENCUESTA_AVISO_GIRO (HEAV_CLIENTE TEXT, HEAV_MODULO TEXT, HEAV_AVISO TEXT, HEAV_GIRO TEXT)
'								skmt.ExecNonQuery2("INSERT INTO HIST_ENCUESTA_AVISO_GIRO(HEAV_CLIENTE , HEAV_MODULO , HEAV_AVISO   ) VALUES (?,?,?) ", Array As Object( clie_id, ENCUESTA, "NO ACEPTA"))
'				
'								B4XPages.ShowPage("productos")
'						End Select
'	
'				
'					Loop
'					result = 	Msgbox2("Entiendo, acepto y consciento que GUNA usará mis datos Personales y serán tratados acorde con lo establecido en la Ley Federal de Protección de Datos Personales en Posesión de los Particulares (en lo sucesivo la “Ley”), y su respectivo Reglamento; bajo lo manifestado en el Aviso de Privacidad – Texto Completo – que se encuentra en la página www.guna.com.mx", "AVISO DE PRIVACIDAD","ACEPTO","", "NO ACEPTO",LoadBitmap(File.DirAssets,"alert2.png"))
'					If result = DialogResponse.Positive Then
				'
'						p_pregunta1.Visible = True
'			
'					Else
'						''HIST_ENCUESTA_AVISO_GIRO (HEAV_CLIENTE TEXT, HEAV_MODULO TEXT, HEAV_AVISO TEXT, HEAV_GIRO TEXT)
'						skmt.ExecNonQuery2("INSERT INTO HIST_ENCUESTA_AVISO_GIRO(HEAV_CLIENTE , HEAV_MODULO , HEAV_AVISO   ) VALUES (?,?,?) ", Array As Object( clie_id, ENCUESTA, "NO ACEPTA"))
'				
'						B4XPages.ShowPage("productos")
'					End If
			Else
				B4XPages.ShowPage("productos")
			End If
		Else
			B4XPages.ShowPage("productos")
		End If
		s.Close
	End If
	
	'Else
'		B4XPages.ShowPage("productos")
	'End If


	
End Sub


Private Sub cb_pregunta_SelectedIndexChanged (Index As Int)
	girotienda = Sender.As(B4XComboBox).SelectedItem
	Log(girotienda)
	Log(Index)
End Sub

Private Sub b_preguntag_Click
	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE kmt_info3 SET CAT_CL_GIRO = ? WHERE CAT_CL_CODIGO = ? And CAT_CL_NOMBRE = ?", Array As Object (girotienda, la_cuenta.text,La_nombre.Text))
	skmt.ExecNonQuery2("INSERT INTO HIST_ENCUESTA_AVISO_GIRO(HEAV_CLIENTE , HEAV_MODULO , HEAV_AVISO ,HEAV_GIRO  ) VALUES (?,?,?,?) ", Array As Object( clie_id, ENCUESTA, "ACEPTA",girotienda))
	If girotienda <> "Selecciona una opcion" Then
		If girotienda = "Tienda de Abarrotes (Abarrotes, Misceláneas, Minisupers, Particulares con Venta y Cremerías)" Then
			Dim result As Int= -3
			Do While result=-3
				result = 	Msgbox2("Entiendo, acepto y consiento que GUNA usará mis datos Personales y serán tratados acorde con lo establecido en la Ley Federal de Protección de Datos Personales en Posesión de los Particulares (en lo sucesivo la “Ley”), y su respectivo Reglamento; bajo lo manifestado en el Aviso de Privacidad – Texto Completo – que se encuentra en la página www.guna.com.mx", "AVISO DE PRIVACIDAD","ACEPTO","", "NO ACEPTO",LoadBitmap(File.DirAssets,"alert2.png"))
				Select Case result
					Case DialogResponse.POSITIVE
'			If ALMACEN = "35" Or ALMACEN  = "43" Or ALMACEN = "54"  Or ALMACEN = "73" Or ALMACEN = "56" Then 'ALMACEN = "7" Then '
'				''Or ALMACEN = "56" ATIZAPAN PEDIGRI
'				p_pregunta1.Visible = False
'				SV_ENCUESTA.Visible = True
'				SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_PED")
'				SV_ENCUESTA.Panel.Height = Panel4.Height
'				Panel4.Visible = True
'				b_like.Visible = False
'				BT_QR.Visible = False
'				B_GALLINA.Visible = False
'				Tar.Visible = False
'				Tels.Visible = False
'				gest.Visible = False
'				b_venta.Visible = False
'				Guardar.Visible = False
'				HIST.Visible = False
'			Else
						Log(que_modulo)
						If que_modulo = Null Or que_modulo = " " Then que_modulo = "1"
						'	Msgbox(que_modulo,"ALO")
						If que_modulo < =  ENCUESTA	Then
							If que_modulo = "1" Then
	
	
								If p_m2.IsInitialized And p_m2.Visible Then
									p_m2.Visible = False
								Else If p_m3.IsInitialized And p_m3.Visible Then
									p_m3.Visible = False
								Else If p_m4.IsInitialized And p_m4.Visible Then
									p_m4.Visible = False
								Else If p_modulo5.IsInitialized And p_modulo5.Visible Then
									p_modulo5.Visible = False
								Else
								End If
								' esto para la primera encuesta m1
								p_pregunta1.Visible = False
								p_cliente.Visible = False
								SV_ENCUESTA.Visible = True
								SV_ENCUESTA.Panel.LoadLayout("ENCUESTA")
								p_m1.Width = Root.Width * 0.94
								SV_ENCUESTA.Panel.Height = p_m1.Height + 60
								Panel7.Visible = False
	
							else if que_modulo = "2" Then
								'' para la m2
								If p_m1.IsInitialized And p_m1.Visible Then
									p_m1.Visible = False
								Else
							
								End If
								p_pregunta1.Visible = False
								p_cliente.Visible = False
								SV_ENCUESTA.Visible = True
								SV_ENCUESTA.Panel.LoadLayout("ESNCUESTA_m2")
								p_m2.Width = Root.Width * 0.94
								SV_ENCUESTA.Panel.Height = p_m2.Height + 60
								Panel7_M2.Visible = False
							else if que_modulo = "3" Then
								'para la m3
								If p_m2.IsInitialized And p_m2.Visible Then
									p_m2.Visible = False
								Else
							
								End If
								p_pregunta1.Visible = False
								p_cliente.Visible = False
								SV_ENCUESTA.Visible = True
								SV_ENCUESTA.Panel.LoadLayout("ENCUESSTA_M3")
				
								p_m3.Width = Root.Width * 0.94
								SV_ENCUESTA.Panel.Height = p_m3.Height + 60
							else if que_modulo = "4" Then
								'' para la m4
								If p_m3.IsInitialized And p_m3.Visible Then
										
									p_m3.Visible = False
								Else
								End If
								p_pregunta1.Visible = False
								p_cliente.Visible = False
								SV_ENCUESTA.Visible = True
								p_pregunta1.Visible = False
								SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M4")
								p_m4.Width = Root.Width * 0.94
								SV_ENCUESTA.Panel.Height = p_m4.Height + 60
			
								Dim Items2 As List
								Items2.Initialize
								Items2.Add("Selecciona una opcion")
								Items2.Add("Propio")
								Items2.Add("Rentado")
								cb_p3_m4.SetItems(Items2)
								itemselect2 = "Selecciona una opcion"
	
								Dim Items3 As List
								Items3.Initialize
								Items3.Add("Selecciona una opcion")
								Items3.Add("Completamente Surtido")
								Items3.Add("Bien Surtido")
								Items3.Add("Poco Surtido")
								Items3.Add("Muy Poco Surtido")
								Items3.Add("Sin Existencias")
								cb_p4_1_m4.SetItems(Items3)
								itemselect3 = "Selecciona una opcion"
								cb_p4_2_m4.SetItems(Items3)
								itemselect4 = "Selecciona una opcion"
								cb_p4_3_m4.SetItems(Items3)
								itemselect5 = "Selecciona una opcion"
								cb_p4_4_m4.SetItems(Items3)
								itemselect6 = "Selecciona una opcion"
								cb_p4_5_m4.SetItems(Items3)
								itemselect7 = "Selecciona una opcion"
							else if que_modulo = "5" Then
								''	'MODULO 5
								If p_m4.IsInitialized And p_m4.Visible Then
									p_m4.Visible = False
								Else
								End If
								p_cliente.Visible = False
								SV_ENCUESTA.Visible = True
								p_pregunta1.Visible = False
								SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M5")
								p_modulo5.Width = Root.Width * 0.94
								SV_ENCUESTA.Panel.Height = p_modulo5.Height + 30
								Dim Items8 As List
								Items8.Initialize
								Items8.Add("Selecciona una opcion")
								Items8.Add("Completamente Surtido")
								Items8.Add("Bien Surtido")
								Items8.Add("Poco Surtido")
								Items8.Add("Muy Poco Surtido")
								Items8.Add("Sin Existencias")
								cb_p1_m5.SetItems(Items8)
								itemselect8 = "Selecciona una opcion"
								cb_p2_m5.SetItems(Items8)
								itemselect9 = "Selecciona una opcion"
								cb_p3_m5.SetItems(Items8)
								itemselect10 = "Selecciona una opcion"
								cb_p4_m5.SetItems(Items8)
								itemselect11 = "Selecciona una opcion"
								cb_p5_m5.SetItems(Items8)
								itemselect12 = "Selecciona una opcion"
								cb_p6_m5.SetItems(Items8)
								itemselect13 = "Selecciona una opcion"
								cb_p7_m5.SetItems(Items8)
								itemselect14 = "Selecciona una opcion"
								cb_p8_m5.SetItems(Items8)
								itemselect15 = "Selecciona una opcion"
								cb_p9_m5.SetItems(Items8)
								itemselect16 = "Selecciona una opcion"
							End If
						Else
							p_pregunta1.Visible = False
							B4XPages.ShowPage("productos")
						End If
'			End IF
					Case DialogResponse.NEGATIVE
						B4XPages.ShowPage("productos")
				End Select
			Loop
			'fin modulos
'	If girotienda = "Tienda de Abarrotes (Abarrotes, Misceláneas, Minisupers, Particulares con Venta y Cremerías)"  Then
'		If  Subs.traeAlmacen = 36  And EXISTE4 = 0 Then
'			p_cliente.Visible = False
'			SV_ENCUESTA.Visible = True
'			p_pregunta1.Visible = False
'			SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M5")
'			p_modulo5.Width = Root.Width * 0.94
'			SV_ENCUESTA.Panel.Height = p_modulo5.Height + 60
'	
'			Dim Items8 As List
'			Items8.Initialize
'			Items8.Add("Selecciona una opcion")
'			Items8.Add("Completamente Surtido")
'			Items8.Add("Bien Surtido")
'			Items8.Add("Poco Surtido")
'			Items8.Add("Muy Poco Surtido")
'			Items8.Add("Sin Existencias")
'			cb_p1_m5.SetItems(Items8)
'			itemselect8 = "Selecciona una opcion"
'			cb_p2_m5.SetItems(Items8)
'			itemselect9 = "Selecciona una opcion"
'			cb_p3_m5.SetItems(Items8)
'			itemselect10 = "Selecciona una opcion"
'			cb_p4_m5.SetItems(Items8)
'			itemselect11 = "Selecciona una opcion"
'			cb_p5_m5.SetItems(Items8)
'			itemselect12 = "Selecciona una opcion"
'			cb_p6_m5.SetItems(Items8)
'			itemselect13 = "Selecciona una opcion"
'			cb_p7_m5.SetItems(Items8)
'			itemselect14 = "Selecciona una opcion"
'			cb_p8_m5.SetItems(Items8)
'			itemselect15 = "Selecciona una opcion"
'			cb_p9_m5.SetItems(Items8)
'			itemselect16 = "Selecciona una opcion"
'			
'		ELSE IF Subs.traeAlmacen = 56 And EXISTE4 = 0 Then
'			p_cliente.Visible = False
'			SV_ENCUESTA.Visible = True
'			p_pregunta1.Visible = False
'			SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M5")
'			p_modulo5.Width = Root.Width * 0.94
'			SV_ENCUESTA.Panel.Height = p_modulo5.Height + 60
'	
'			Dim Items8 As List
'			Items8.Initialize
'			Items8.Add("Selecciona una opcion")
'			Items8.Add("Completamente Surtido")
'			Items8.Add("Bien Surtido")
'			Items8.Add("Poco Surtido")
'			Items8.Add("Muy Poco Surtido")
'			Items8.Add("Sin Existencias")
'			cb_p1_m5.SetItems(Items8)
'			itemselect8 = "Selecciona una opcion"
'			cb_p2_m5.SetItems(Items8)
'			itemselect9 = "Selecciona una opcion"
'			cb_p3_m5.SetItems(Items8)
'			itemselect10 = "Selecciona una opcion"
'			cb_p4_m5.SetItems(Items8)
'			itemselect11 = "Selecciona una opcion"
'			cb_p5_m5.SetItems(Items8)
'			itemselect12 = "Selecciona una opcion"
'			cb_p6_m5.SetItems(Items8)
'			itemselect13 = "Selecciona una opcion"
'			cb_p7_m5.SetItems(Items8)
'			itemselect14 = "Selecciona una opcion"
'			cb_p8_m5.SetItems(Items8)
'			itemselect15 = "Selecciona una opcion"
'			cb_p9_m5.SetItems(Items8)
'			itemselect16 = "Selecciona una opcion"
			'
'		Else If Subs.traeAlmacen = 4  And EXISTE5 = 0 Then
'			p_cliente.Visible = False
'			SV_ENCUESTA.Visible = True
'			p_pregunta1.Visible = False
'			SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M5")
'			p_modulo5.Width = Root.Width * 0.94
'			SV_ENCUESTA.Panel.Height = p_modulo5.Height + 60
'	
'			Dim Items8 As List
'			Items8.Initialize
'			Items8.Add("Selecciona una opcion")
'			Items8.Add("Completamente Surtido")
'			Items8.Add("Bien Surtido")
'			Items8.Add("Poco Surtido")
'			Items8.Add("Muy Poco Surtido")
'			Items8.Add("Sin Existencias")
'			cb_p1_m5.SetItems(Items8)
'			itemselect8 = "Selecciona una opcion"
'			cb_p2_m5.SetItems(Items8)
'			itemselect9 = "Selecciona una opcion"
'			cb_p3_m5.SetItems(Items8)
'			itemselect10 = "Selecciona una opcion"
'			cb_p4_m5.SetItems(Items8)
'			itemselect11 = "Selecciona una opcion"
'			cb_p5_m5.SetItems(Items8)
'			itemselect12 = "Selecciona una opcion"
'			cb_p6_m5.SetItems(Items8)
'			itemselect13 = "Selecciona una opcion"
'			cb_p7_m5.SetItems(Items8)
'			itemselect14 = "Selecciona una opcion"
'			cb_p8_m5.SetItems(Items8)
'			itemselect15 = "Selecciona una opcion"
'			cb_p9_m5.SetItems(Items8)
'			itemselect16 = "Selecciona una opcion"
			' FIN MODULO 5


			' ESTOI ES PARA MODULO 4
'			p_cliente.Visible = False
'			SV_ENCUESTA.Visible = True
'			p_pregunta1.Visible = False
'			SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M4")
'			Panel5.Width = Root.Width * 0.94
'			SV_ENCUESTA.Panel.Height = Panel5.Height + 60
'			
'			Dim Items2 As List
'			Items2.Initialize
'			Items2.Add("Selecciona una opcion")
'			Items2.Add("Propio")
'			Items2.Add("Rentado")
'			cb_p3_m4.SetItems(Items2)
'			itemselect2 = "Selecciona una opcion"
'	
'			Dim Items3 As List
'			Items3.Initialize
'			Items3.Add("Selecciona una opcion")
'			Items3.Add("Completamente Surtido")
'			Items3.Add("Bien Surtido")
'			Items3.Add("Poco Surtido")
'			Items3.Add("Muy Poco Surtido")
'			Items3.Add("Sin Existencias")
'			cb_p4_1_m4.SetItems(Items3)
'			itemselect3 = "Selecciona una opcion"
'			cb_p4_2_m4.SetItems(Items3)
'			itemselect4 = "Selecciona una opcion"
'			cb_p4_3_m4.SetItems(Items3)
'			itemselect5 = "Selecciona una opcion"
'			cb_p4_4_m4.SetItems(Items3)
'			itemselect6 = "Selecciona una opcion"
'			cb_p4_5_m4.SetItems(Items3)
'			itemselect7 = "Selecciona una opcion"
'		End If
			' FIN MODULO 4
'	Else
'		B4XPages.ShowPage("productos")
'	End If
		Else
			p_pregunta1.Visible = False
			B4XPages.ShowPage("productos")
		End If
	Else
		Msgbox("Contesta la pregunta por favor","AVISO")
	End If
End Sub

Private Sub cb_p3_m4_SelectedIndexChanged (Index As Int)
	itemselect2 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect2)
	Log(Index)
End Sub

Private Sub cb_p4_1_m4_SelectedIndexChanged (Index As Int)
	itemselect3 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect3)
	Log(Index)
End Sub

Private Sub cb_p4_2_m4_SelectedIndexChanged (Index As Int)
	itemselect4 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect4)
	Log(Index)
End Sub

Private Sub cb_p4_3_m4_SelectedIndexChanged (Index As Int)
	itemselect5 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect5)
	Log(Index)
End Sub

Private Sub cb_p4_4_m4_SelectedIndexChanged (Index As Int)
	itemselect6 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect6)
	Log(Index)
End Sub

Private Sub cb_p4_5_m4_SelectedIndexChanged (Index As Int)
	itemselect7 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect7)
	Log(Index)
End Sub

Private Sub cb_p1_m5_SelectedIndexChanged (Index As Int)
	itemselect8 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect8)
	Log(Index)
End Sub

Private Sub cb_p2_m5_SelectedIndexChanged (Index As Int)
	itemselect9 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect9)
	Log(Index)
End Sub

Private Sub cb_p3_m5_SelectedIndexChanged (Index As Int)
	itemselect10 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect10)
	Log(Index)
End Sub

Private Sub cb_p4_m5_SelectedIndexChanged (Index As Int)
	itemselect11 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect11)
	Log(Index)
End Sub

Private Sub cb_p5_m5_SelectedIndexChanged (Index As Int)
	itemselect12 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect12)
	Log(Index)
End Sub

Private Sub cb_p6_m5_SelectedIndexChanged (Index As Int)
	itemselect13 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect13)
	Log(Index)
End Sub

Private Sub cb_p7_m5_SelectedIndexChanged (Index As Int)
	itemselect14 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect14)
	Log(Index)
End Sub

Private Sub cb_p8_m5_SelectedIndexChanged (Index As Int)
	itemselect15 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect15)
	Log(Index)
End Sub

Private Sub cb_p9_m5_SelectedIndexChanged (Index As Int)
	itemselect16 = Sender.As(B4XComboBox).SelectedItem
	Log(itemselect16)
	Log(Index)
End Sub


Sub B_guardaencuesta_Click
	Dim SI_GUARDAR As String
	SI_GUARDAR = 1
	
	If RB1_E1.Checked = False And RB2_E1.Checked = False And RB3_E1.Checked = False Then
		SI_GUARDAR = 0
	End If
	
	If Panel7.Visible = True Then
		If RadioButton15.Checked = False And RadioButton16.Checked = False And RadioButton17.Checked = False Then
			SI_GUARDAR = 0
		End If
	End If
	
	If RadioButton1.Checked = False And  RadioButton2.Checked = False And RadioButton3.Checked = False And RadioButton4.Checked = False Then
		SI_GUARDAR = 0
	End If
	
	If RadioButton5.Checked = False And  RadioButton6.Checked = False And RadioButton7.Checked = False And RadioButton8.Checked = False  And RadioButton9.Checked = False Then
		SI_GUARDAR = 0
	End If
	
	If RadioButton10.Checked = False And  RadioButton11.Checked = False And RadioButton12.Checked = False And RadioButton13.Checked = False  And RadioButton14.Checked = False Then
		SI_GUARDAR = 0
	End If
	
	If p6.Text = "" Then
		SI_GUARDAR = 0
	End If
	If p7.Text = "" Then
		SI_GUARDAR = 0
	End If
	If p8.Text = "" Then
		SI_GUARDAR = 0
	End If
	
	If CheckBox1.Checked = False And CheckBox2.Checked = False And CheckBox3.Checked = False And CheckBox4.Checked = False And CheckBox5.Checked = False And CheckBox6.Checked = False And CheckBox7.Checked = False And CheckBox8.Checked = False Then
		encuentasmapa.Put("P9", "")
		Log(encuentasmapa)
	End If
	
	If SI_GUARDAR = 1 Then
		skmt.ExecNonQuery2("INSERT INTO ENCUESTA_MODULO1 (CLIENTE, ALMACEN,P1, P2, P3, P4, P5, P6, P7, P8, P9) VALUES (?,?,?,?,?,?,?,?,?,?,?)", Array As Object(Subs.traeCliente, ALMACEN, encuentasmapa.Get("P3"),encuentasmapa.Get("P1"),encuentasmapa.Get("P2"),encuentasmapa.Get("P4"),encuentasmapa.Get("P5"),p6.Text,p7.Text,p8.Text,encuentasmapa.Get("P9")))
'	SV_ENCUESTA.Visible = False
'	p_cliente.Visible = True
'	B4XPages.MainPage.tipo_venta = "PREVENTA"
'	B4XPages.ShowPage("productos")
'	MsgboxAsync("Encuesta guardada","")
		RB1_E1.Checked = False
		RB2_E1.Checked = False
		RB3_E1.Checked = False
		RadioButton15.Checked = False
		RadioButton16.Checked = False
		RadioButton17.Checked = False
		RadioButton1.Checked = False
		RadioButton2.Checked = False
		RadioButton3.Checked = False
		RadioButton4.Checked = False
		RadioButton5.Checked = False
		RadioButton6.Checked = False
		RadioButton7.Checked = False
		RadioButton8.Checked = False
		RadioButton9.Checked = False
		RadioButton10.Checked = False
		RadioButton11.Checked = False
		RadioButton12.Checked = False
		RadioButton13.Checked = False
		RadioButton14.Checked = False
		p6.Text = ""
		p7.Text = ""
		p8.Text = ""
		CheckBox1.Checked = False
		CheckBox2.Checked = False
		CheckBox3.Checked = False
		CheckBox4.Checked = False
		CheckBox5.Checked = False
		CheckBox6.Checked = False
		CheckBox7.Checked = False
		CheckBox8.Checked = False
	
		If ENCUESTA > 1 Then
			' para la m2
			If p_m1.IsInitialized And p_m1.Visible Then
				p_m1.Visible = False
			Else
							
			End If
			p_pregunta1.Visible = False
			p_cliente.Visible = False
			SV_ENCUESTA.Visible = True
			SV_ENCUESTA.Panel.LoadLayout("ESNCUESTA_m2")
			p_m2.Width = Root.Width * 0.94
			SV_ENCUESTA.Panel.Height = p_m2.Height + 60
			Panel7_M2.Visible = False
		Else
			p_pregunta1.Visible = False
			SV_ENCUESTA.Visible = False
			p_cliente.Visible = True
'			tipo_venta = "PREVENTA"
'			StartActivity(colonia2)
			B4XPages.ShowPage("productos")
		End If
	Else
		Msgbox("FALTAN DATOS DE CAPTURA FAVOR DE VALIDAR", "AVISO")
	End If
End Sub

Sub Tels_Click
	B4XPages.ShowPage("NoVenta")
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
'	BACK key pressed
'	Return True To close, False To cancel
	cuest.encuestaIniciada = False
	cuest.ocultPanelPregunta
	If bitacora.p_transparenteInicioFin2.Visible And bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VISITA" Then
		ToastMessageShow("Por favor presione el botón de TERMINAR VISITA", True)
		Return False
	Else if Subs.hayPedido Then
		ToastMessageShow("Por favor presione el botón de GUARDAR", True)
		Return False
	else If p_encuesta.Visible Then
		p_encuesta.Visible = False
	else If scv_bat.Visible Then
		scv_bat.Visible = False
	Else iF p_camara.Visible Then
		p_camara.Visible = False
		StopCamera2
		Return False
	else If p_pregunta1.Visible Then
		p_pregunta1.Visible = False
	Else if SV_ENCUESTA.Visible Then
		SV_ENCUESTA.visible = False
		p_cliente.Visible = True
'	Else If B4XPages.MainPage.nota Then
	Else
		Starter.enCliente = False
		B4XPages.ShowPage("Clientes")
	End If
'	Return True
	Return False
End Sub

Sub Tar_Click
	B4XPages.ShowPage("Nota")
End Sub

Sub DATOS_Click
	B4XPages.ShowPage("telefonos")
End Sub

Sub Guardar_Click
	Guardar.SendToBack
	bitacora.b_Inicio_Fin_venta2.Text = "TERMINAR VISITA"
	bitacora.enVenta = False
	bitacora.inicioFin
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
	c.Position=0
	clie_id = c.GetString("CUENTA")
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, COUNT(*) AS CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	c.Position=0

	'AQUI CAMBIAR
	Private s3 As Cursor=B4XPages.MainPage.skmt.ExecQuery2("select * FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_RECALCULO <> ? AND PE_RECALCULO <> ? AND PE_RECALCULO <> ?",Array As String("","null",Null))
'	LogColor(s3.RowCount,Colors.Yellow)
	Private suma As Float = 0
	If s3.RowCount > 0 Then
		Private s As Cursor=B4XPages.MainPage.skmt.ExecQuery2("select iFNULL(sum(pe_costo_tot),0) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_RECALCULO = ? AND PE_RECALCULO = ? AND PE_RECALCULO = ?",Array As String("","null",Null))
		s.Position = 0
		Private s5 As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select iFNULL(sum(PE_RECALCULOTOT),0) as TOTAL_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_RECALCULO <> ? AND PE_RECALCULO <> ? AND PE_RECALCULO <> ?",Array As String("","null",Null))
		s5.Position = 0
		suma = s.GetString("TOTAL_CLIE") + s5.GetString("TOTAL_CLIE")
		s.Close
	Else If s3.RowCount = 0 Then
		Private s As Cursor=B4XPages.MainPage.skmt.ExecQuery("select iFNULL(sum(pe_costo_tot),0) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
		s.Position=0
		suma = s.GetString("TOTAL_CLIE")
		s.Close
	End If
	'AQUI TERMINA
	If c.GetString("CUANTOS") > 0 Then
		Private cbFactura As Int = 0
		If CH_FACTURA.Checked Then cbFactura = 1
		B4XPages.MainPage.skmt.ExecNonQuery("delete from NOVENTA where NV_CLIENTE In (select cuenta from cuentaa)")
		B4XPages.MainPage.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
		B4XPages.MainPage.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_FACTURA,PC_ALMACEN,PC_RUTA) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),NumberFormat2(suma,0,2,2,False), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps,cbFactura,Subs.traeAlmacen,Subs.traeRuta))
		B4XPages.MainPage.skmt.ExecNonQuery("UPDATE kmt_info3 set gestion = 2  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
'		B4XPages.MainPage.skmt.ExecNonQuery("delete from TICKET_IMPRESO where idCliente In (select cuenta from cuentaa)")
'		B4XPages.MainPage.skmt.ExecNonQuery($"insert into TICKET_IMPRESO (idCliente) values ('${Subs.traeCliente}')"$)
	End If
	c.Close
	DateTime.TimeFormat = "HHmmss"
	sTime=DateTime.Time(DateTime.Now)
	B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_OUT = ?  where HSS_OUT = 0 AND  HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(sTime))
	'  B4XPages.MainPage.skmt.ExecNonQuery("UPDATE HIST_STAY_STORE set HSS_TOT = HSS_OUT - HSS_IN where HSS_CODIGO In (select cuenta from cuentaa)")
	Try
		c=B4XPages.MainPage.skmt.ExecQuery(" Select (substr(HSS_OUT,1,2) - substr(HSS_IN,1,2)) - Case when  (substr(HSS_OUT,3,2) - substr(HSS_IN,3,2)) < 0 Then 1 Else 0 end HORAS_TOTALES, " & _
	"Case when  (substr(HSS_OUT,3,2) - substr(HSS_IN,3,2)) < 0 Then (substr(HSS_OUT,3,2) + 60 - substr(HSS_IN,3,2)) " & _
	"	Else (substr(HSS_OUT,3,2) - substr(HSS_IN,3,2)) End - Case when  (substr(HSS_OUT,5,2) - substr(HSS_IN,5,2)) < 0 Then 1 Else 0 end  MINUTOS_TOTALES, " & _
	"Case when  (substr(HSS_OUT,5,2) - substr(HSS_IN,5,2)) < 0 Then (substr(HSS_OUT,5,2) + 60 - substr(HSS_IN,5,2)) " & _
	"	Else (substr(HSS_OUT,5,2) - substr(HSS_IN,5,2)) end SEGUNDOS_TOTALES " & _
	"	from HIST_STAY_STORE where HSS_CODIGO In (Select cuenta from cuentaa) ")
		c.Position = 0
		stay_hh = c.GetString("HORAS_TOTALES") * 60 * 60
		stay_mi = c.GetString("MINUTOS_TOTALES") * 60
		stay_ss = c.GetString("SEGUNDOS_TOTALES")
		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_STORE set HSS_TOT = ?  where HSS_CODIGO In (select cuenta from cuentaa)", Array As Object(stay_hh + stay_mi + stay_ss))
		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE HIST_STAY_OUT set HSO_FIN = ?  ", Array As Object(sTime))
		c.Close
	Catch
		ToastMessageShow(".",True)
	End Try
	DateTime.TimeFormat = "HH:mm:ss"
	'##########################  INICIA CODIGO PARA CREDITOS ####################
	Log(BCREDITO)
'	If BCREDITO = 1 And suma > 0 Then
'		Msgbox2Async("¿La venta va a ser a crédito o contado?" , "AVISO", "Crédito", "", "Efectivo", LoadBitmap(File.DirAssets,"alert2.png"), False)
'		Wait For Msgbox_Result (resultado As Int)
'		If resultado = DialogResponse.POSITIVE Then
''			ToastMessageShow("Positivo", False)
'			mandaWAMsgCredito(telefono.Trim, suma)
'		Else
''			ToastMessageShow("Efectivo", False)
'		End If
''		ToastMessageShow("ENVIAR MSG WA POR MONTO $XXX", False)
'	End If
	'##########################  TERMINA CODIGO PARA CREDITOS ####################
'	B4XPages.ShowPage("Principal")
End Sub

Sub Guardar_LongClick
'	bitacora.p_transparenteInicioFin2.Visible = True
'	bitacora.b_Inicio_Fin_venta2.text = "TERMINAR VENTA"
End Sub

Sub guardadoventa
	
End Sub

Sub NUEVO_Click
	B4XPages.ShowPage("NuevoCliente")
End Sub

Sub HIST_Click
	B4XPages.ShowPage("historicobat")
End Sub

Sub BT_QR_Click
	sc.isportrait = True
	sc.timeoutDuration = 45
	sc.theViewFinderXfactor = 0.7
	sc.theViewFinderYfactor = 0.5
	sc.theResultColor = Colors.Green
	sc.mustVibrate = True
	sc.BeginScan("sc")
End Sub

Sub sc_result(atype As String,Values As String, image As Bitmap)
	'Log("Type : " & atype)
	'Log("Value : " & Values)
	CODIGO = Values
	DD=B4XPages.MainPage.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM kmt_info3 WHERE CAT_CL_NUM_SERIEFISICO = ?", Array As String(CODIGO))
	DD.Position =0
	If DD.GetString("CUANTOS") > 0 Then
		MsgboxAsync("Código ya asignado", "AVISO")
	Else
		If CODIGO.Length = 7 Then
			Msgbox2Async("El código "& CODIGO & " es correcto?" , "Title", "Yes", "Cancel", "No", Null, False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE kmt_info3 set CAT_CL_NUM_SERIEFISICO = ?, CAT_CL_LONG = ?, CAT_CL_LAT =? where CAT_CL_CODIGO In (select cuenta from cuentaa)", Array As Object(CODIGO, B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps))
				L_QR.TEXT =CODIGO
				L_QR.TextColor = Colors.Blue
				B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_CODIGO_BARRAS(CODIGOKMTS, CODIGOB, LAT, LON) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text,CODIGO, B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps))
			End If
		Else
			MsgboxAsync("Código No Valido", "AVISO")
		End If
	End If
	DD.Close
End Sub

Sub sc_timedout(timedOut As Boolean)
	Log("timedOut " & timedOut)
End Sub

Sub sc_usercancelled(userCancelled As Boolean)
	Log("userCancelled " & userCancelled)
End Sub

Sub calc_ean_checksum(number As String) As String           'this has now become redundant as I am only interested in QR Codes
	Dim i As Int
	Dim cO As Char
	Dim soma As Int
	Dim n As Int
	Dim digit As Float
	soma = 0
	For i=0 To number.Length - 1
		digit = number.SubString2(i,i+1)
		n= digit * ((i Mod 2) * 2 + 1)
		soma=soma+n
	Next
	Return number & ( ( 10 - ( soma Mod 10 )) Mod 10 )
End Sub

Sub b_mapa_Click
	B4XPages.ShowPage("mapas")
End Sub

Sub B_IMP_Click
'	Printer1.Connect2
'	c=Starter.skmt.ExecQuery2("select count(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("PERFIL"))
'	c.Position =0
'	perfil = c.GetString("CUANTOS")
'	c.Close
	
'	If perfil > 0 Then
'	c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("PERFIL"))
'	If c.RowCount > 0 Then
'		c.Position =0
'		perfil = c.GetString("CAT_VA_VALOR")
'		c.Close
'	End If
'	LogColor(perfil,Colors.Magenta)
'	End If
	
	If ALMACEN = 87 Then
		If Subs.traemontoprod Then
			Impresion2
		Else
			Impresion
		End If
	Else If ALMACEN = 88 Or ALMACEN = 94 Then
		
		Impresion4
	Else If ALMACEN = 81 Or ALMACEN = 102 Then
		
		c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_BCREDITO,0) AS CAT_CL_BCREDITO, CAT_CL_LIMITECREDITO, IFNULL(CONFIRMADO,0) AS CONFIRMADO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position = 0
		
		If c.GetString("CAT_CL_BCREDITO") = 0 Then
			Impresion4
			
		Else If c.GetString("CAT_CL_BCREDITO") = 1 Then
			If c.GetString("CONFIRMADO") = 0 Then
			
				Msgbox2Async("La entrega sera a credito o de contado?" , "Atención", "Credito", "Contado", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
				Wait For Msgbox_Result (resultado As Int)
				If resultado = DialogResponse.POSITIVE Then
					Dim creditocod As Cursor = Starter.skmt.ExecQuery("SELECT CODIGO FROM CODIGOS_CREDITO WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
					Log(creditocod.RowCount)
					If creditocod.RowCount > 0 Then
						creditocod.Position = 0
						Dim cs As CSBuilder
						cs.Initialize

						' 1. Iniciamos el constructor y definimos el tamaño general más grande (ej. 20)
						cs.Size(16).Append("Proporciona el siguiente codigo al cliente '")

						' 2. Activamos Negrita (Bold) para el código
						cs.Bold.Append(creditocod.GetString("CODIGO")).Pop ' .Pop cierra la negrita

						' 3. Continuamos con el texto normal y cerramos todo
						cs.Append("' para su entrega").PopAll

						' 4. Pasamos el objeto 'cs' en lugar del texto plano
						Msgbox2Async(cs, "Atención", "Ok", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
						Wait For Msgbox_Result (resultado As Int)
						If resultado = DialogResponse.POSITIVE Then
							Starter.skmt.ExecNonQuery("Update kmt_info3 set CONFIRMADO = 1  WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
							Starter.skmt.ExecNonQuery("Update CODIGOS_CREDITO set BANDERA = 1  WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
						
							Impresion4
						End If
					Else
						Impresion4
					End If
				
				
				Else If resultado = DialogResponse.CANCEL Then
					Starter.skmt.ExecNonQuery("Update kmt_info3 set CONFIRMADO = 1  WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
					Impresion4
				End If
			Else
				Impresion4
			End If
		End If
		
	Else 
		Impresion
	End If
	
	B4XPages.MainPage.skmt.ExecNonQuery("delete from TICKET_IMPRESO where idCliente In (select cuenta from cuentaa)")
	B4XPages.MainPage.skmt.ExecNonQuery($"insert into TICKET_IMPRESO (idCliente) values ('${Subs.traeCliente}')"$)
End Sub

Sub Impresion4
	Dim pedinow As Cursor = skmt.ExecQuery("select * FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_FUTURO = '0' ")
	If pedinow.RowCount > 0 Then
'		Mandapedido
	
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
'	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.DateFormat = "dd/MM/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL"))
'	c.Position = 0
'	sucursal = c.GetString("CAT_VA_VALOR")
'	c.Close
	Public Const eLINEFEED As String = "" & Chr(0x0D) & Chr(0x0A)
	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 21
	BLANCO = " "
'	Dim bmp As Bitmap
'	bmp.InitializeResize(File.DirAssets, "guna.png", 192, 192, True) 'ignore
'	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
'	
'	myimage = Printer1.DitherImage2D(myimage, 128)
'	
'	myimage= Printer1.PackImage(myimage)
'	Printer1.WriteString(eLINEFEED) ' nudge the printer to show the user something is happening
'	Printer1.WriteString(Printer1.REVERSE)
'	
'	Printer1.PrintImage(myimage)
'	Printer1.WriteString(Printer1.UNREVERSE)

'	Printer1.Justify = 1
'	printer.Initialize(cmp20.OutputStream)
	Printer1.WriteString("Centro de atencion a Clientes Bat" &  eLINEFEED)
	Printer1.WriteString("Telefono: 800 400 5000" &  eLINEFEED)
	Printer1.WriteString(eLINEFEED)
	Printer1.WriteString(eLINEFEED)


	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  eLINEFEED)
	Printer1.WriteString("RFC: DRT-110316-9J1" &  eLINEFEED)
'	Printer1.WriteString(sucursal &  eLINEFEED)
	Printer1.WriteString(sDate &  eLINEFEED)
	Printer1.WriteString(sTime &  eLINEFEED)
	Printer1.WriteString("Vendedor:" & usuario &  eLINEFEED)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  eLINEFEED)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  eLINEFEED)
	Printer1.WriteString("Calle: " & la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("Colonia: " & la_col.Text &  eLINEFEED)
'	Printer1.WriteString("C.P.: " & la_cp.Text &  eLINEFEED)
	Printer1.WriteString("Entre calle1: " & l_entre1.Text &  eLINEFEED)
	Printer1.WriteString("Entre Calle2: " & l_entre2.Text &  eLINEFEED)

	Printer1.WriteString("--------------------PREVENTA--------------------" &  eLINEFEED)
	' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
	s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, IFNULL(PE_RECALCULO,0) AS PE_RECALCULO, length(PE_COSTOU) as L_COSTOU, length(Ifnull(PE_RECALCULO,0)) as L_COSTOREC, PE_CANT * PE_COSTOU AS PE_COSTO_TOT, PE_CANT * IFNULL(PE_RECALCULO,0) AS  PE_COSTO_TOTREC, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT, length(PE_CANT * IFNULL(PE_RECALCULO,0)) as L_COSTO_TOTREC, PE_PROID, PE_CEDIS, PE_RECCANT FROM PEDIDO WHERE PE_CEDIS = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_FUTURO = '0' order by  PE_PROID", Array As String(Subs.traeAlmacen))
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
'				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
			Else
				If s.GetInt("PE_RECALCULO") = 0 Then
					Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOU") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO

					ESPACIO = ESPACIO - TAMANO

					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED&  eLINEFEED )
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				Else if s.GetInt("PE_CANT") = s.GetInt("PE_RECCANT") Then
					Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOTREC") + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next

					Dim descpro As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_PD_RANGO, CAT_PD_DESCUENTO, CAT_PD_RANGO2 FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}') AND INSTR(',' || CAT_PD_TIER || ',' , ',${Subs.traeTipoCliente},') > 0 "$)
					descpro.Position = 0
					
					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_RECALCULO") & "   $" & s.GETSTRING("PE_COSTO_TOTREC") &  eLINEFEED &  eLINEFEED )

						Log(s.GetString("PE_PRONOMBRE"))
						Log(descpro.GetDouble("CAT_PD_DESCUENTO"))
					Printer1.WriteString(BLANCO & "PL $" & s.GETSTRING("PE_COSTOU") & " Desc.: " & descpro.GetDouble("CAT_PD_DESCUENTO")&"%" &  eLINEFEED &  eLINEFEED)
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				Else if s.GetInt("PE_CANT") <> s.GetInt("PE_RECCANT") Then
					Log(s.GetInt("PE_RECCANT"))
					Log(s.GetInt("PE_CANT"))
					Log("aqui")
					Printer1.WriteString(s.GetString("PE_RECCANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOTREC") + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					
'					Con descuento
					Dim descpro As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_PD_RANGO, CAT_PD_DESCUENTO, CAT_PD_RANGO2 FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}') AND INSTR(',' || CAT_PD_TIER || ',' , ',${Subs.traeTipoCliente},') > 0 "$)
					descpro.Position = 0

					Printer1.WriteString(BLANCO & s.GETSTRING("PE_RECCANT") & " X $" & s.GETSTRING("PE_RECALCULO") & "   $" & NumberFormat2((s.GETSTRING("PE_RECCANT") * s.GETSTRING("PE_RECALCULO")),1,2,2,False) &  eLINEFEED &  eLINEFEED )
					Printer1.WriteString(BLANCO & "PL $" & s.GETSTRING("PE_COSTOU") & " Desc.: " & descpro.GetDouble("CAT_PD_DESCUENTO")&"%" &  eLINEFEED &  eLINEFEED)

					Private subTot As String = (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) * s.GETSTRING("PE_COSTOU")
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = subTot + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
'					Sin decuento
					Printer1.WriteString((s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					Printer1.WriteString(BLANCO & (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & NumberFormat2(subTot,1,2,2,False) &  eLINEFEED &  eLINEFEED )
					
					
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				End If
			End If
		Next
	End If
	s.Close
'	Printer1.WriteString(" " &  eLINEFEED)

		totalpromos = 0
		totalpromostotal = 0
	s=skmt.ExecQuery("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE LENGTH(PE_CEDIS) > 3  AND PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_FUTURO = '0' order by  PE_CEDIS, PE_COSTOU")
	If S.RowCount>0 Then
'		Printer1.WriteString("------------------PROMOCIONES-------------------" &  eLINEFEED)
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
'				Printer1.WriteString("* " & s.GetString("PE_PRONOMBRE") &" *" &  eLINEFEED)
				
			Else
				
				Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				TAMANO = s.GetLong("L_CANT") + TAMANO
				TAMANO = s.GetLong("L_COSTOU") + TAMANO
				TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
				ESPACIO = ESPACIO - TAMANO
	
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
				
					
					Dim coloressaldo As Cursor=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_CLASIFICADOR2,0) AS CAT_CL_CLASIFICADOR2 from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
					coloressaldo.Position = 0
				
					If coloressaldo.GetString("CAT_CL_CLASIFICADOR2") = "LP222_D" Then
				
						Dim precioprom As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_LISTAPRECIO AS CAT_GP_PRECIO FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}' "$)
					Else
						Dim precioprom As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_GP_PRECIO FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}' "$)
					End If
				
					If precioprom.RowCount > 0 Then
						precioprom.Position = 0
						Log (precioprom.GETSTRING("CAT_GP_PRECIO"))
						Log (s.GETSTRING("PE_COSTOU"))
						If NumberFormat2(precioprom.GETSTRING("CAT_GP_PRECIO"),0.,2,2,False) <> NumberFormat2(s.GETSTRING("PE_COSTOU"),0.,2,2,False) Then
						
							Printer1.WriteString(BLANCO & "PL $" & precioprom.GETSTRING("CAT_GP_PRECIO") & " Desc.: " & NumberFormat2(((( precioprom.GETSTRING("CAT_GP_PRECIO")-s.GETSTRING("PE_COSTOU"))*100)/precioprom.GETSTRING("CAT_GP_PRECIO")),0.,2,2,False) &"%" &  eLINEFEED &  eLINEFEED)
						End If
					
				End If
				TAMANO = 0
				ESPACIO = 21
				BLANCO = " "
			End If
		Next
		Printer1.WriteString(" " &  eLINEFEED)
	End If
	s.Close
	
'	s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_FUTURO = '0'")
'	s.Position =0
'	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
'	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
'	'	End If
'	Printer1.WriteString("Subtotal Preventa:   $" & s.GetString("TOTAL") &  eLINEFEED)
''	Printer1.WriteString("Subtotal Preventa:   $" & Subs.calculaTotalConPromoXRango(Subs.traeCliente) &  eLINEFEED)
'	
'	c= skmt.ExecQuery("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) and PE_FUTURO = '0'")
'	C.Position=0
'	Printer1.WriteString("Total Articulos:   " & c.GetString("PC_NOART") &  eLINEFEED)
'	c.Close
'	Dim s3 As Cursor =skmt.ExecQuery("select IFNULL(SUM(PE_COSTO_TOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) = 0 and PE_FUTURO = '0'")
'	s3.Position =0
'	S2=skmt.ExecQuery("select IFNULL(SUM(PE_RECALCULOTOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) <> 0 and PE_FUTURO = '0'")
'	S2.Position =0
'	
'	If NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False) <> s.GetString("TOTAL") Then
'		
'		Printer1.WriteString("Descuento:   $" & NumberFormat2( (s.GetString("TOTAL") - Subs.calculaTotalConPromoXRango2(Subs.traeCliente)),0,2,2,False)&  eLINEFEED)
'	End If
'	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
'	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
'	'	End If
''	Printer1.WriteString("Descuento:   $" & 150 &  eLINEFEED)
''	Printer1.WriteString("Total Preventa:   $" & NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False)&  eLINEFEED)
'	Printer1.WriteString("Total Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango2(Subs.traeCliente),0,2,2,False)&  eLINEFEED)
	
		Printer1.WriteString("Subtotal Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango3(Subs.traeCliente),0,2,2,False)&  eLINEFEED)
		If NumberFormat2(Subs.calculaTotalConPromoXRango3(Subs.traeCliente),0,2,2,False) <> NumberFormat2(Subs.calculaTotalConPromoXRango2(Subs.traeCliente),0,2,2,False) Then
			Printer1.WriteString("Descuento:   $" & NumberFormat2( (Subs.calculaTotalConPromoXRango3(Subs.traeCliente) - Subs.calculaTotalConPromoXRango2(Subs.traeCliente)),0,2,2,False)&  eLINEFEED)
'			Printer1.WriteString("Descuento %:   " & NumberFormat2( (((Subs.calculaTotalConPromoXRango3(Subs.traeCliente) - Subs.calculaTotalConPromoXRango2(Subs.traeCliente))*100)/NumberFormat2(Subs.calculaTotalConPromoXRango3(Subs.traeCliente),0,2,2,False)),0,2,2,False)&  eLINEFEED)
		End If
		Printer1.WriteString("Total Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango2(Subs.traeCliente),0,2,2,False)&  eLINEFEED)
		Printer1.WriteString(" " &  eLINEFEED)
		
		Private contadocredito As Cursor = Starter.skmt.ExecQuery($"SELECT BANDERA FROM CODIGOS_CREDITO WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA) "$)
		If contadocredito.RowCount > 0 Then
			contadocredito.Position = 0
			If contadocredito.getstring("BANDERA") = "1" Then
				Printer1.WriteString("Tipo de entrega:   CREDITO"&eLINEFEED)
			Else
				Printer1.WriteString("Tipo de entrega:   CONTADO"&  eLINEFEED)
			End If
		End If
		
		Printer1.WriteString(" " &  eLINEFEED)
		Printer1.WriteString("------------------------------------------------" &  eLINEFEED)
		Printer1.WriteString("ENTREGA EN :" &  eLINEFEED)
		Printer1.WriteString(la_Calle.Text &  eLINEFEED)
		Printer1.WriteString("--------------ESTE TICKET NO ES UN--------------" &  eLINEFEED)
		Printer1.WriteString("----------COMPROBANTE FISCAL, SOLO ES-----------" &  eLINEFEED)
		Printer1.WriteString("------------------INFORMATIVO-------------------" &  eLINEFEED)
		Printer1.WriteString("------------------------------------------------" &  eLINEFEED)
		If ALMACEN = 81 Then
		
			Dim creditocod2 As Cursor = Starter.skmt.ExecQuery("SELECT BANDERA FROM CODIGOS_CREDITO WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
			If creditocod2.RowCount > 0 Then
				creditocod2.Position = 0
				If creditocod2.GetString("BANDERA") = "1" Then
					Dim creditocod As Cursor = Starter.skmt.ExecQuery("SELECT CODIGO FROM CODIGOS_CREDITO WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
					creditocod.Position = 0
					Printer1.WriteString("------------------CODIGO: "&  creditocod.GetString("CODIGO")& "------------------" &  eLINEFEED)
					Printer1.WriteString("------------------------------------------------" &  eLINEFEED)
				End If
			End If
		End If
		
		Printer1.WriteString(" " &  eLINEFEED)
	
	Sleep(1000)
	Printer1.DisConnect
	
	ProgressDialogHide
	End If
'	printer.Flush
	'	printer.Close
	Sleep(1000)
	Dim pedifutu As Cursor = skmt.ExecQuery("select * FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_FUTURO = '1' ")
	If pedifutu.RowCount > 0 Then
		Impresion5
	End If
End Sub

Sub Mandapedido
'	PEDIDO
	c=B4XPages.MainPage.skmt.ExecQuery2("SELECT PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO FROM PEDIDO WHERE (PE_RECALCULO = ? or PE_RECALCULO = ? or PE_RECALCULO IS NULL)",Array As String("","null"))
	Dim d As Cursor=B4XPages.MainPage.skmt.ExecQuery("SELECT COUNT(*) as CUANTOS_PEDIDO FROM PEDIDO")
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "insert_pedido_GV2"
			cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"), ALMACEN, C.GetString("PE_COSTO_TOT"), C.GetString("PE_COSTOU"), C.GetString("PE_CANT"), C.GetString("PE_PRONOMBRE"), C.GetString("PE_PROID"), C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
			B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "ins_pedido")
		Next
	End If
	c.Close
	d.Position=0

'	cuantos_pedido = D.GetString("CUANTOS_PEDIDO")
	d.Close

	' UPDATE VENTA CREDITO
	''   UPDATE GUNA.CAT_CLIENTES SET CAT_CL_CTA = (?) WHERE cat_cl_codigo = (?) AND CAT_CL_IDALMACEN = (?) AND CAT_CL_RUTA = (?)
	c=B4XPages.MainPage.skmt.ExecQuery("Select * from CODIGOS_CREDITO where BANDERA = 1")
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "update_ventacredito_guna"
			cmd.Parameters = Array As Object(C.GetString("BANDERA"),C.GetString("CLIENTE"),ALMACEN,Subs.traeRuta2(C.GetString("CLIENTE")))
			B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "up_coordenadas")
		Next
	End If
	c.Close

'		If ALMACEN = "88" Or ALMACEN = "6" Then
	c=B4XPages.MainPage.skmt.ExecQuery2("SELECT PE_RECALCULO,PE_RECALCULOTOT,ifnull(PE_RECCEDIS,'') as PE_RECCEDIS,PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,ifnull(PE_CANT,0) as PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO, PE_COSTO_SIN, PE_RUTA, PE_DESC, PE_FOLIO, IFNULL(PE_RECCANT,0) AS PE_RECCANT FROM PEDIDO WHERE PE_RECALCULO <> ? or PE_RECALCULO <> ? or PE_RECALCULO IS NOT NULL",Array As String("","null"))
	d=B4XPages.MainPage.skmt.ExecQuery($"SELECT COUNT(*) as CUANTOS_PEDIDO FROM PEDIDO where PE_RUTA = '${Subs.traeRuta}'"$)
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			If c.GetString("PE_RECCEDIS") = "" Then
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "insert_pedido_GV2"
				cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"), ALMACEN, C.GetString("PE_RECALCULOTOT"), C.GetString("PE_RECALCULO"), C.GetString("PE_CANT"), C.GetString("PE_PRONOMBRE"), C.GetString("PE_PROID"), C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
				B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "ins_pedido")
			Else
				If c.GetString("PE_RECCANT") = c.GetString("PE_CANT") Then
					Dim cmd As DBCommand
					cmd.Initialize
					cmd.Name = "insert_pedido_GV2"
					cmd.Parameters = Array As Object(C.GetString("PE_RECCEDIS"), ALMACEN, C.GetString("PE_RECALCULOTOT"), C.GetString("PE_RECALCULO"), C.GetString("PE_CANT"), C.GetString("PE_PRONOMBRE"), C.GetString("PE_PROID"), C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
					B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "ins_pedido")
				Else
					'Con descuento
					Dim cmd As DBCommand
					cmd.Initialize
					cmd.Name = "insert_pedido_GV2"
					cmd.Parameters = Array As Object(C.GetString("PE_RECCEDIS"), ALMACEN, C.GetString("PE_RECALCULOTOT"), C.GetString("PE_RECALCULO"), C.GetString("PE_RECCANT"), C.GetString("PE_PRONOMBRE"), C.GetString("PE_PROID"), C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
					B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "ins_pedido")
					'Sin descuento
					Dim cmd As DBCommand
					cmd.Initialize
					cmd.Name = "insert_pedido_GV2"
					cmd.Parameters = Array As Object(C.GetString("PE_CEDIS"), ALMACEN, NumberFormat2((C.GetString("PE_CANT")-C.GetString("PE_RECCANT"))*C.GetString("PE_COSTOU"),1,2,2,False), C.GetString("PE_COSTOU"), (C.GetString("PE_CANT")-C.GetString("PE_RECCANT")), C.GetString("PE_PRONOMBRE"), C.GetString("PE_PROID"), C.GetString("PE_CLIENTE"),C.GetString("PE_FECHA"),C.GetString("PE_USUARIO"),C.GetString("PE_RUTA"), C.GetString("PE_COSTO_SIN"),C.GetString("PE_DESC"),c.GetString("PE_FOLIO"))
					B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "ins_pedido")
				End If
			End If
		Next
	End If
	c.Close
	d.Position=0
'	cuantos_pedido = D.GetString("CUANTOS_PEDIDO")
	d.Close
End Sub

Sub Impresion5
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
'	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.DateFormat = "dd/MM/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL"))
'	c.Position = 0
'	sucursal = c.GetString("CAT_VA_VALOR")
'	c.Close
	Public Const eLINEFEED As String = "" & Chr(0x0D) & Chr(0x0A)
	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 21
	BLANCO = " "
'	Dim bmp As Bitmap
'	bmp.InitializeResize(File.DirAssets, "guna.png", 192, 192, True) 'ignore
'	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
'	
'	myimage = Printer1.DitherImage2D(myimage, 128)
'	
'	myimage= Printer1.PackImage(myimage)
'	Printer1.WriteString(eLINEFEED) ' nudge the printer to show the user something is happening
'	Printer1.WriteString(Printer1.REVERSE)
'	
'	Printer1.PrintImage(myimage)
'	Printer1.WriteString(Printer1.UNREVERSE)

'	Printer1.Justify = 1
'	printer.Initialize(cmp20.OutputStream)
	Printer1.WriteString("Centro de atencion a Clientes Bat" &  eLINEFEED)
	Printer1.WriteString("Telefono: 800 400 5000" &  eLINEFEED)
	Printer1.WriteString(eLINEFEED)
	Printer1.WriteString(eLINEFEED)
	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  eLINEFEED)
	Printer1.WriteString("RFC: DRT-110316-9J1" &  eLINEFEED)
'	Printer1.WriteString(sucursal &  eLINEFEED)
	Printer1.WriteString(sDate &  eLINEFEED)
	Printer1.WriteString(sTime &  eLINEFEED)
	Printer1.WriteString("Vendedor:" & usuario &  eLINEFEED)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  eLINEFEED)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  eLINEFEED)
	Printer1.WriteString("Calle: " & la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("Colonia: " & la_col.Text &  eLINEFEED)
'	Printer1.WriteString("C.P.: " & la_cp.Text &  eLINEFEED)
	Printer1.WriteString("Entre calle1: " & l_entre1.Text &  eLINEFEED)
	Printer1.WriteString("Entre Calle2: " & l_entre2.Text &  eLINEFEED)
	
	Printer1.WriteString("--------------PEDIDO PREACORDADO----------------" &  eLINEFEED)
	' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
	s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, IFNULL(PE_RECALCULO,0) AS PE_RECALCULO, length(PE_COSTOU) as L_COSTOU, length(Ifnull(PE_RECALCULO,0)) as L_COSTOREC, PE_CANT * PE_COSTOU AS PE_COSTO_TOT, PE_CANT * IFNULL(PE_RECALCULO,0) AS  PE_COSTO_TOTREC, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT, length(PE_CANT * IFNULL(PE_RECALCULO,0)) as L_COSTO_TOTREC, PE_PROID, PE_CEDIS, PE_RECCANT FROM PEDIDO WHERE PE_CEDIS = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_FUTURO = '1' order by  PE_PROID", Array As String(Subs.traeAlmacen))
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
			Else
				If s.GetInt("PE_RECALCULO") = 0 Then
					Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOU") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO

					ESPACIO = ESPACIO - TAMANO

					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED&  eLINEFEED )
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				Else if s.GetInt("PE_CANT") = s.GetInt("PE_RECCANT") Then
					Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOTREC") + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next

					Dim descpro As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_PD_RANGO, CAT_PD_DESCUENTO, CAT_PD_RANGO2 FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}') AND INSTR(',' || CAT_PD_TIER || ',' , ',${Subs.traeTipoCliente},') > 0 "$)
					descpro.Position = 0

					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_RECALCULO") & "   $" & s.GETSTRING("PE_COSTO_TOTREC") &  eLINEFEED &  eLINEFEED )

					Printer1.WriteString(BLANCO & "PL $" & s.GETSTRING("PE_COSTOU") & " Desc.: " & descpro.GetDouble("CAT_PD_DESCUENTO")&"%" &  eLINEFEED &  eLINEFEED)
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				Else if s.GetInt("PE_CANT") <> s.GetInt("PE_RECCANT") Then
					Log(s.GetInt("PE_RECCANT"))
					Log(s.GetInt("PE_CANT"))
					Log("aqui")
					Printer1.WriteString(s.GetString("PE_RECCANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOTREC") + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					
'					Con descuento
					Dim descpro As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_PD_RANGO, CAT_PD_DESCUENTO, CAT_PD_RANGO2 FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}') AND INSTR(',' || CAT_PD_TIER || ',' , ',${Subs.traeTipoCliente},') > 0 "$)
					descpro.Position = 0

					Printer1.WriteString(BLANCO & s.GETSTRING("PE_RECCANT") & " X $" & s.GETSTRING("PE_RECALCULO") & "   $" & NumberFormat2((s.GETSTRING("PE_RECCANT") * s.GETSTRING("PE_RECALCULO")),1,2,2,False) &  eLINEFEED &  eLINEFEED )
					Printer1.WriteString(BLANCO & "PL $" & s.GETSTRING("PE_COSTOU") & " Desc.: " & descpro.GetDouble("CAT_PD_DESCUENTO")&"%" &  eLINEFEED &  eLINEFEED)

					Private subTot As String = (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) * s.GETSTRING("PE_COSTOU")
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = subTot + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
'					Sin decuento
					Printer1.WriteString((s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					Printer1.WriteString(BLANCO & (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & NumberFormat2(subTot,1,2,2,False) &  eLINEFEED &  eLINEFEED )
					
					
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				End If
			End If
		Next
	End If
	s.Close
'	Printer1.WriteString(" " &  eLINEFEED)
	s=skmt.ExecQuery("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE LENGTH(PE_CEDIS) > 3  AND PE_CLIENTE IN (Select CUENTA from cuentaa)  and PE_FUTURO = '1' order by  PE_CEDIS, PE_COSTOU")
	If S.RowCount>0 Then
'		Printer1.WriteString("------------------PROMOCIONES-------------------" &  eLINEFEED)
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
'				Printer1.WriteString("* " & s.GetString("PE_PRONOMBRE") &" *" &  eLINEFEED)
				
			Else
				
				Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				TAMANO = s.GetLong("L_CANT") + TAMANO
				TAMANO = s.GetLong("L_COSTOU") + TAMANO
				TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
				ESPACIO = ESPACIO - TAMANO
	
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
				Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
				
				Dim precioprom As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_GP_PRECIO FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}' "$)
				If precioprom.RowCount > 0 Then
					precioprom.Position = 0
					Log (precioprom.GETSTRING("CAT_GP_PRECIO"))
					Log (s.GETSTRING("PE_COSTOU"))
					If NumberFormat2(precioprom.GETSTRING("CAT_GP_PRECIO"),0.,2,2,False) <> NumberFormat2(s.GETSTRING("PE_COSTOU"),0.,2,2,False) Then
						
						Printer1.WriteString(BLANCO & "PL $" & precioprom.GETSTRING("CAT_GP_PRECIO") & " Desc.: " & NumberFormat2(((( precioprom.GETSTRING("CAT_GP_PRECIO")-s.GETSTRING("PE_COSTOU"))*100)/precioprom.GETSTRING("CAT_GP_PRECIO")),0.,2,2,False) &"%" &  eLINEFEED &  eLINEFEED)
					End If
					
				End If
				TAMANO = 0
				ESPACIO = 21
				BLANCO = " "
			End If
		Next
		Printer1.WriteString(" " &  eLINEFEED)
	End If
	s.Close
	
'	s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and PE_FUTURO = '1'")
'	s.Position =0
'	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
'	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
'	'	End If
'	Printer1.WriteString("Subtotal Preventa:   $" & s.GetString("TOTAL") &  eLINEFEED)
''	Printer1.WriteString("Subtotal Preventa:   $" & Subs.calculaTotalConPromoXRango(Subs.traeCliente) &  eLINEFEED)
'	
'	c= skmt.ExecQuery("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) and PE_FUTURO = '1'")
'	C.Position=0
'	Printer1.WriteString("Total Articulos:   " & c.GetString("PC_NOART") &  eLINEFEED)
'	c.Close
'	Dim s3 As Cursor =skmt.ExecQuery("select IFNULL(SUM(PE_COSTO_TOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) = 0 and PE_FUTURO = '1'")
'	s3.Position =0
'	S2=skmt.ExecQuery("select IFNULL(SUM(PE_RECALCULOTOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) <> 0 and PE_FUTURO = '1'")
'	S2.Position =0
'	
'	If NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False) <> s.GetString("TOTAL") Then
'		
'		Printer1.WriteString("Descuento:   $" & NumberFormat2( (s.GetString("TOTAL") - Subs.calculaTotalConPromoXRango1(Subs.traeCliente)),0,2,2,False)&  eLINEFEED)
'	End If
'	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
'	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
'	'	End If
''	Printer1.WriteString("Descuento:   $" & 150 &  eLINEFEED)
''	Printer1.WriteString("Total Preventa:   $" & NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False)&  eLINEFEED)
'	Printer1.WriteString("Total Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango1(Subs.traeCliente),0,2,2,False)&  eLINEFEED)


	Printer1.WriteString("Subtotal Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango4(Subs.traeCliente),0,2,2,False)&  eLINEFEED)
	If NumberFormat2(Subs.calculaTotalConPromoXRango4(Subs.traeCliente),0,2,2,False) <> NumberFormat2(Subs.calculaTotalConPromoXRango1(Subs.traeCliente),0,2,2,False) Then
		Printer1.WriteString("Descuento:   $" & NumberFormat2( (Subs.calculaTotalConPromoXRango4(Subs.traeCliente) - Subs.calculaTotalConPromoXRango1(Subs.traeCliente)),0,2,2,False)&  eLINEFEED)
'		Printer1.WriteString("Descuento %:   " & NumberFormat2( (((Subs.calculaTotalConPromoXRango4(Subs.traeCliente) - Subs.calculaTotalConPromoXRango1(Subs.traeCliente))*100)/NumberFormat2(Subs.calculaTotalConPromoXRango4(Subs.traeCliente),0,2,2,False)),0,2,2,False)&  eLINEFEED)
	End If
	Printer1.WriteString("Total Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango1(Subs.traeCliente),0,2,2,False)&  eLINEFEED)
	
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString("------------------------------------------------" &  eLINEFEED)
	Printer1.WriteString("ENTREGA EN :" &  eLINEFEED)
	Printer1.WriteString(la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("--------------ESTE TICKET NO ES UN--------------" &  eLINEFEED)
	Printer1.WriteString("----------COMPROBANTE FISCAL, SOLO ES-----------" &  eLINEFEED)
	Printer1.WriteString("------------------INFORMATIVO-------------------" &  eLINEFEED)
	Printer1.WriteString("------------------------------------------------" &  eLINEFEED)
	
	If ALMACEN = 81 Then
		
		Dim creditocod2 As Cursor = Starter.skmt.ExecQuery("SELECT BANDERA FROM CODIGOS_CREDITO WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		If creditocod2.RowCount > 0 Then
			creditocod2.Position = 0
			If creditocod2.GetString("BANDERA") = "1" Then
				Dim creditocod As Cursor = Starter.skmt.ExecQuery("SELECT CODIGO FROM CODIGOS_CREDITO WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
				creditocod.Position = 0
				Printer1.WriteString("------------------CODIGO: "&  creditocod.GetString("CODIGO")& "------------------" &  eLINEFEED)
				Printer1.WriteString("------------------------------------------------" &  eLINEFEED)
			End If
		End If
	End If
	Printer1.WriteString(" " &  eLINEFEED)
	
	
	Sleep(1000)
	Printer1.DisConnect
	
	ProgressDialogHide
'	printer.Flush
	'	printer.Close
End Sub

Private Sub b_preventa2_LongClick
'	Log(NumberFormat2(Subs.calculaTotalConPromoXRango3(Subs.traeCliente),0,2,2,False))
	Log(NumberFormat2(Subs.calculaTotalConPromoXRango4(Subs.traeCliente),0,2,2,False))
	Log(NumberFormat2(Subs.calculaTotalConPromoXRango1(Subs.traeCliente),0,2,2,False))
	Log(NumberFormat2( (Subs.calculaTotalConPromoXRango4(Subs.traeCliente) - Subs.calculaTotalConPromoXRango1(Subs.traeCliente)	),0,2,2,False)	)
	Log(NumberFormat2( (((Subs.calculaTotalConPromoXRango4(Subs.traeCliente) - Subs.calculaTotalConPromoXRango1(Subs.traeCliente))*100)/NumberFormat2(Subs.calculaTotalConPromoXRango4(Subs.traeCliente),0,2,2,False)),0,2,2,False))
	
	
End Sub

Sub Impresion3
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
'	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.DateFormat = "dd/MM/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL"))
'	c.Position = 0
'	sucursal = c.GetString("CAT_VA_VALOR")
'	c.Close
	Public Const eLINEFEED As String = "" & Chr(0x0D) & Chr(0x0A)
	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 21
	BLANCO = " "
'	Dim bmp As Bitmap
'	bmp.InitializeResize(File.DirAssets, "guna.png", 192, 192, True) 'ignore
'	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
'	
'	myimage = Printer1.DitherImage2D(myimage, 128)
'	
'	myimage= Printer1.PackImage(myimage)
'	Printer1.WriteString(eLINEFEED) ' nudge the printer to show the user something is happening
'	Printer1.WriteString(Printer1.REVERSE)
'	
'	Printer1.PrintImage(myimage)
'	Printer1.WriteString(Printer1.UNREVERSE)

	'Printer1.Justify = 1
	'printer.Initialize(cmp20.OutputStream)
'	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  eLINEFEED)
	Printer1.WriteString("RFC: DRT-110316-9J1" &  eLINEFEED)
'	Printer1.WriteString(sucursal &  eLINEFEED)
	Printer1.WriteString(sDate &  eLINEFEED)
	Printer1.WriteString(sTime &  eLINEFEED)
	Printer1.WriteString("Vendedor:" & usuario &  eLINEFEED)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  eLINEFEED)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  eLINEFEED)
	Printer1.WriteString("Calle: " & la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("Colonia: " & la_col.Text &  eLINEFEED)
'	Printer1.WriteString("C.P.: " & la_cp.Text &  eLINEFEED)
	Printer1.WriteString("Entre calle1: " & l_entre1.Text &  eLINEFEED)
	Printer1.WriteString("Entre Calle2: " & l_entre2.Text &  eLINEFEED)

	Printer1.WriteString("-----------PREVENTA-----------" &  eLINEFEED)
	' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
	s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, IFNULL(PE_RECALCULO,0) AS PE_RECALCULO, length(PE_COSTOU) as L_COSTOU, length(Ifnull(PE_RECALCULO,0)) as L_COSTOREC, PE_CANT * PE_COSTOU AS PE_COSTO_TOT, PE_CANT * IFNULL(PE_RECALCULO,0) AS  PE_COSTO_TOTREC, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT, length(PE_CANT * IFNULL(PE_RECALCULO,0)) as L_COSTO_TOTREC, PE_PROID, PE_CEDIS, PE_RECCANT FROM PEDIDO WHERE PE_CEDIS = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by  PE_PROID", Array As String(Subs.traeAlmacen))
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
			Else
				If s.GetInt("PE_RECALCULO") = 0 Then
					Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOU") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO

					ESPACIO = ESPACIO - TAMANO

					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED&  eLINEFEED )
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				Else if s.GetInt("PE_CANT") = s.GetInt("PE_RECCANT") Then
					Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOTREC") + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next

					Dim descpro As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_PD_RANGO, CAT_PD_DESCUENTO, CAT_PD_RANGO2 FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}') AND INSTR(',' || CAT_PD_TIER || ',' , ',${Subs.traeTipoCliente},') > 0 "$)
					descpro.Position = 0

					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_RECALCULO") & "   $" & s.GETSTRING("PE_COSTO_TOTREC") &  eLINEFEED &  eLINEFEED )

					Printer1.WriteString(BLANCO & "PL $" & s.GETSTRING("PE_COSTOU") & " Desc.: " & descpro.GetDouble("CAT_PD_DESCUENTO")&"%" &  eLINEFEED &  eLINEFEED)
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				Else if s.GetInt("PE_CANT") <> s.GetInt("PE_RECCANT") Then
					Log(s.GetInt("PE_RECCANT"))
					Log(s.GetInt("PE_CANT"))
					Log("aqui")
					Printer1.WriteString(s.GetString("PE_RECCANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = s.GetLong("L_COSTO_TOTREC") + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					
'					Con descuento
					Dim descpro As Cursor = Starter.skmt.ExecQuery($"SELECT CAT_PD_RANGO, CAT_PD_DESCUENTO, CAT_PD_RANGO2 FROM CAT_PROMOS_DESCUENTOS WHERE CAT_PD_PRODUCTO IN (SELECT CAT_GP_ID FROM CAT_GUNAPROD WHERE CAT_GP_NOMBRE = '${s.GetString("PE_PRONOMBRE")}') AND INSTR(',' || CAT_PD_TIER || ',' , ',${Subs.traeTipoCliente},') > 0 "$)
					descpro.Position = 0

					Printer1.WriteString(BLANCO & s.GETSTRING("PE_RECCANT") & " X $" & s.GETSTRING("PE_RECALCULO") & "   $" & NumberFormat2((s.GETSTRING("PE_RECCANT") * s.GETSTRING("PE_RECALCULO")),1,2,2,False) &  eLINEFEED &  eLINEFEED )
					Printer1.WriteString(BLANCO & "PL $" & s.GETSTRING("PE_COSTOU") & " Desc.: " & descpro.GetDouble("CAT_PD_DESCUENTO")&"%" &  eLINEFEED &  eLINEFEED)

					Private subTot As String = (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) * s.GETSTRING("PE_COSTOU")
					TAMANO = s.GetLong("L_CANT") + TAMANO
					TAMANO = s.GetLong("L_COSTOREC") + TAMANO
					TAMANO = subTot + TAMANO

					ESPACIO = ESPACIO - TAMANO
	
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
'					Sin decuento
					Printer1.WriteString((s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
					Printer1.WriteString(BLANCO & (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & NumberFormat2(subTot,1,2,2,False) &  eLINEFEED &  eLINEFEED )
					
					
					TAMANO = 0
					ESPACIO = 21
					BLANCO = " "
				End If
			End If
		Next
	End If
	s.Close
	Printer1.WriteString(" " &  eLINEFEED)
	s=skmt.ExecQuery("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE LENGTH(PE_CEDIS) > 3 AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_CEDIS, PE_COSTOU")
	If S.RowCount>0 Then
		Printer1.WriteString("------------PROMOS------------" &  eLINEFEED)
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				
			Else
				
				Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				TAMANO = s.GetLong("L_CANT") + TAMANO
				TAMANO = s.GetLong("L_COSTOU") + TAMANO
				TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
				ESPACIO = ESPACIO - TAMANO
	
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
				Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
				TAMANO = 0
				ESPACIO = 21
				BLANCO = " "
			End If
		Next
		Printer1.WriteString(" " &  eLINEFEED)
	End If
	s.Close
	
	s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position =0
	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
	'	End If
	Printer1.WriteString("Subtotal Preventa:   $" & s.GetString("TOTAL") &  eLINEFEED)
'	Printer1.WriteString("Subtotal Preventa:   $" & Subs.calculaTotalConPromoXRango(Subs.traeCliente) &  eLINEFEED)
	
	c= skmt.ExecQuery("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP )")
	C.Position=0
	Printer1.WriteString("Total Articulos:   " & c.GetString("PC_NOART") &  eLINEFEED)
	c.Close
	Dim s3 As Cursor =skmt.ExecQuery("select IFNULL(SUM(PE_COSTO_TOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) = 0")
	s3.Position =0
	S2=skmt.ExecQuery("select IFNULL(SUM(PE_RECALCULOTOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) <> 0")
	S2.Position =0
	
	If NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False) <> s.GetString("TOTAL") Then
		
		Printer1.WriteString("Descuento:   $" & NumberFormat2( (s.GetString("TOTAL") - Subs.calculaTotalConPromoXRango(Subs.traeCliente)),0,2,2,False)&  eLINEFEED)
	End If
	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
	'	End If
'	Printer1.WriteString("Descuento:   $" & 150 &  eLINEFEED)
'	Printer1.WriteString("Total Preventa:   $" & NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False)&  eLINEFEED)
	Printer1.WriteString("Total Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango(Subs.traeCliente),0,2,2,False)&  eLINEFEED)
	
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString("ENTREGA EN :" &  eLINEFEED)
	Printer1.WriteString(la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("----ESTE TICKET NO ES UN -----" &  eLINEFEED)
	Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" &  eLINEFEED)
	Printer1.WriteString("--------INFORMATIVO-----------" &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	
	Sleep(1000)
	Printer1.DisConnect
	
	ProgressDialogHide
'	printer.Flush
	'	printer.Close
End Sub

Sub Impresion2
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	DateTime.DateFormat = "dd/MM/yyyy"
'	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL"))
'	c.Position = 0
'	sucursal = c.GetString("CAT_VA_VALOR")
'	c.Close
	Public Const eLINEFEED As String = "" & Chr(0x0D) & Chr(0x0A)
	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 21
	BLANCO = " "
'	Dim bmp As Bitmap
'	bmp.InitializeResize(File.DirAssets, "guna.png", 192, 192, True) 'ignore
'	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
'	
'	myimage = Printer1.DitherImage2D(myimage, 128)
'	
'	myimage= Printer1.PackImage(myimage)
'	Printer1.WriteString(eLINEFEED) ' nudge the printer to show the user something is happening
'	Printer1.WriteString(Printer1.REVERSE)
'	
'	Printer1.PrintImage(myimage)
'	Printer1.WriteString(Printer1.UNREVERSE)

	'Printer1.Justify = 1
	'printer.Initialize(cmp20.OutputStream)
'	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  eLINEFEED)
	Printer1.WriteString("RFC: DRT-110316-9J1" &  eLINEFEED)
'	Printer1.WriteString(sucursal &  eLINEFEED)
	Printer1.WriteString(sDate &  eLINEFEED)
	Printer1.WriteString(sTime &  eLINEFEED)
	Printer1.WriteString("Vendedor:" & usuario &  eLINEFEED)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  eLINEFEED)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  eLINEFEED)
	Printer1.WriteString("Calle: " & la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("Colonia: " & la_col.Text &  eLINEFEED)
'	Printer1.WriteString("C.P.: " & la_cp.Text &  eLINEFEED)
	Printer1.WriteString("Entre calle1: " & l_entre1.Text &  eLINEFEED)
	Printer1.WriteString("Entre Calle2: " & l_entre2.Text &  eLINEFEED)
	
	Printer1.WriteString("-----------PREVENTA-----------" &  eLINEFEED)
	' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
	s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_CEDIS <> ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("DUR"))
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				
			Else
				
				Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				TAMANO = s.GetLong("L_CANT") + TAMANO
				TAMANO = s.GetLong("L_COSTOU") + TAMANO
				TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
				ESPACIO = ESPACIO - TAMANO
	
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
				Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
				TAMANO = 0
				ESPACIO = 21
				BLANCO = " "
			End If
		Next
	End If
	s.Close
	Printer1.WriteString(" " &  eLINEFEED)
	s=skmt.ExecQuery("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE LENGTH(PE_CEDIS) > 3 AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_CEDIS, PE_COSTOU")
	If S.RowCount>0 Then
		Printer1.WriteString("------------PROMOS------------" &  eLINEFEED)
		For i=0 To S.RowCount -1
			S.Position=i
			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				
			Else
				
				Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				TAMANO = s.GetLong("L_CANT") + TAMANO
				TAMANO = s.GetLong("L_COSTOU") + TAMANO
				TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
				ESPACIO = ESPACIO - TAMANO
	
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
				Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
				TAMANO = 0
				ESPACIO = 21
				BLANCO = " "
			End If
		Next
		Printer1.WriteString(" " &  eLINEFEED)
	End If
	s.Close
	
	s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position =0
	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
	'	End If
	Printer1.WriteString("Subtotal Preventa:   $" & s.GetString("TOTAL") &  eLINEFEED)
	s.Close
	c= skmt.ExecQuery("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP )")
	C.Position=0
	Printer1.WriteString("Total Articulos:   " & c.GetString("PC_NOART") &  eLINEFEED)
	c.Close
	s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position =0
	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
	'	End If
	Printer1.WriteString("Descuento:   $" & 150 &  eLINEFEED)
	Printer1.WriteString("Total Preventa:   $" & (s.GetString("TOTAL") -150 )&  eLINEFEED)
	
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString("ENTREGA EN :" &  eLINEFEED)
	Printer1.WriteString(la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("----ESTE TICKET NO ES UN -----" &  eLINEFEED)
	Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" &  eLINEFEED)
	Printer1.WriteString("--------INFORMATIVO-----------" &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	
	Sleep(1000)
	Printer1.DisConnect
	
	ProgressDialogHide
'	printer.Flush
	'	printer.Close
End Sub

Sub Impresion
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
'	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.DateFormat = "dd/MM/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c.Close
'	c=Starter.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =?", Array As String ("SUCURSAL"))
'	c.Position = 0
'	sucursal = c.GetString("CAT_VA_VALOR")
'	c.Close
	Public Const eLINEFEED As String = "" & Chr(0x0D) & Chr(0x0A)
	ProgressDialogShow("Imprimiendo, un momento ...")
	Printer1.DisConnect
	If Not(Printer1.IsConnected) Then
'		If logger Then Log("conectando 1")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada)
			Sleep(1000)
			cont = cont + 1
			If cont = 7 Then Printer1.Connect 'Tratamos de reconectar
			If cont > 15 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	Else
'		If logger Then Log("conectando 2")
		Printer1.Connect
		Private cont As Int = 0
		Do While Not(impresoraConectada) Or Not(Printer1.IsConnected)
			Sleep(1000)
			cont = cont + 1
			If cont = 2 Then Printer1.Connect
			If cont > 4 Then impresoraConectada = True
		Loop
		Sleep(500)
		impresoraConectada = False
	End If
	
	TAMANO = 0
	ESPACIO = 21
	BLANCO = " "
'	Dim bmp As Bitmap
'	bmp.InitializeResize(File.DirAssets, "guna.png", 192, 192, True) 'ignore
'	Dim myimage As AnImage = Printer1.ImageToBWIMage(bmp)
'	
'	myimage = Printer1.DitherImage2D(myimage, 128)
'	
'	myimage= Printer1.PackImage(myimage)
'	Printer1.WriteString(eLINEFEED) ' nudge the printer to show the user something is happening
'	Printer1.WriteString(Printer1.REVERSE)
'	
'	Printer1.PrintImage(myimage)
'	Printer1.WriteString(Printer1.UNREVERSE)

	'Printer1.Justify = 1
	'printer.Initialize(cmp20.OutputStream)
'	Printer1.WriteString("DISTRIBUIDORA ROCHA TULA PACHUCA" &  eLINEFEED)
	Printer1.WriteString("RFC: DRT-110316-9J1" &  eLINEFEED)
'	Printer1.WriteString(sucursal &  eLINEFEED)
	Printer1.WriteString(sDate &  eLINEFEED)
	Printer1.WriteString(sTime &  eLINEFEED)
	Printer1.WriteString("Vendedor:" & usuario &  eLINEFEED)
	Printer1.WriteString("Tienda: " & La_nombre.Text &  eLINEFEED)
	Printer1.WriteString("ID.Cliente: " &  la_cuenta.Text &  eLINEFEED)
	Printer1.WriteString("Calle: " & la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("Colonia: " & la_col.Text &  eLINEFEED)
'	Printer1.WriteString("C.P.: " & la_cp.Text &  eLINEFEED)
	Printer1.WriteString("Entre calle1: " & l_entre1.Text &  eLINEFEED)
	Printer1.WriteString("Entre Calle2: " & l_entre2.Text &  eLINEFEED)
	
	Printer1.WriteString("-----------PREVENTA-----------" &  eLINEFEED)
	' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
'	s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_CEDIS <> ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("DUR"))
	s=skmt.ExecQuery2("select PE_PRONOMBRE, SUM(PE_CANT) AS PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,SUM(PE_CANT) * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_CEDIS <> ?  AND PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_COSTOU > 0.01  GROUP by  PE_PROID", Array As String("DUR"))
	If S.RowCount>0 Then
		For i=0 To S.RowCount -1
			S.Position=i
'			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				
'			Else
				
'				Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				TAMANO = s.GetLong("L_CANT") + TAMANO
				TAMANO = s.GetLong("L_COSTOU") + TAMANO
				TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
				ESPACIO = ESPACIO - TAMANO
	
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
				Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
				TAMANO = 0
				ESPACIO = 21
				BLANCO = " "
'			End If
		Next
	End If
	s.Close
	Printer1.WriteString(" " &  eLINEFEED)
'	s=skmt.ExecQuery("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE LENGTH(PE_CEDIS) > 3 AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_CEDIS, PE_COSTOU")
	s=skmt.ExecQuery2("select PE_PRONOMBRE, SUM(PE_CANT) AS PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,SUM(PE_CANT) * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_CEDIS <> ?  AND PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_COSTOU = 0.01  GROUP by  PE_PROID", Array As String("DUR"))

	If S.RowCount>0 Then
		Printer1.WriteString("--------BONIFICACIONES--------" &  eLINEFEED)
		For i=0 To S.RowCount -1
			S.Position=i
'			If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
				Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				
'			Else
				
'				Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
				TAMANO = s.GetLong("L_CANT") + TAMANO
				TAMANO = s.GetLong("L_COSTOU") + TAMANO
				TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
	
				ESPACIO = ESPACIO - TAMANO
	
				For E=0 To ESPACIO -1
					BLANCO = " " & BLANCO
				Next
				Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
				TAMANO = 0
				ESPACIO = 21
				BLANCO = " "
'			End If
		Next
		Printer1.WriteString(" " &  eLINEFEED)
	End If
	s.Close
		
'		Printer1.WriteString("-------------RMI..-----------" &  eLINEFEED)
'		' aqui es donde esta el pedo de julieta de los descuentos quitar el precio2 pero meter un if para saber si es ruta especial o es normal o que show.
'		s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_TIPO = ? AND PE_CEDIS = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA","DUR"))
'		If S.RowCount>0 Then
'			For i=0 To S.RowCount -1
'				S.Position=i
'				If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
'					Printer1.WriteString(s.GetString("PE_PRONOMBRE") &  eLINEFEED)
'				
'				Else
'				
'					Printer1.WriteString(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE") &  eLINEFEED)
'					TAMANO = s.GetLong("L_CANT") + TAMANO
'					TAMANO = s.GetLong("L_COSTOU") + TAMANO
'					TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
'	
'					ESPACIO = ESPACIO - TAMANO
'	
'					For E=0 To ESPACIO -1
'						BLANCO = " " & BLANCO
'					Next
'					Printer1.WriteString(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") &  eLINEFEED )
'					TAMANO = 0
'					ESPACIO = 21
'					BLANCO = " "
'				End If
'			Next
'		End If
'		s.Close
		
	s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	s.Position =0
	'	If s.GetString("TOTAL") - s.GetString("TOTAL2") <> 0 Then
	'		Printer1.WriteString("Descuento:     $" & 	 (s.GetString("TOTAL2") -  s.GetString("TOTAL")))
	'	End If
	Printer1.WriteString("Total Preventa:   $" & s.GetString("TOTAL") &  eLINEFEED)
	s.Close
	c= skmt.ExecQuery("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP )")
	C.Position=0
	Printer1.WriteString("Total Articulos:   " & c.GetString("PC_NOART") &  eLINEFEED)
	c.Close
	
	Printer1.WriteString(" " &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString("ENTREGA EN :" &  eLINEFEED)
	Printer1.WriteString(la_Calle.Text &  eLINEFEED)
	Printer1.WriteString("----ESTE TICKET NO ES UN -----" &  eLINEFEED)
	Printer1.WriteString("--COMPROBANTE FISCAL, SOLO ES-" &  eLINEFEED)
	Printer1.WriteString("--------INFORMATIVO-----------" &  eLINEFEED)
	Printer1.WriteString("------------------------------" &  eLINEFEED)
	Printer1.WriteString(" " &  eLINEFEED)
	
	Sleep(1000)
	Printer1.DisConnect
	
	ProgressDialogHide
'	printer.Flush
	'	printer.Close
End Sub

'Sub B_IMP_Click
'	TAMANO = 0
'	ESPACIO = 21
'	BLANCO = " "
'	printer.Initialize(cmp20.OutputStream)
'	printer.WriteLine("DURAKELO S.A. de C.V.")
'	printer.WriteLine("RFC: DUR-011025-T12")
'	printer.WriteLine("Tel.: 618-826-0104")
'	printer.WriteLine("Vendedor: KMTS ")
'	printer.WriteLine("Tienda: " & La_nombre.Text)
'	printer.WriteLine("-----------PREVENTA-----------")
'	s=B4XPages.MainPage.skmt.ExecQuery("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU, PE_COSTO_TOT, length(PE_COSTO_TOT) as L_COSTO_TOT FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
'	If S.RowCount>0 Then
'		For i=0 To S.RowCount -1
'			S.Position=i
'			printer.WriteLine(s.GetString("PE_CANT") & " " & s.GetString("PE_PRONOMBRE"))
'			TAMANO = s.GetLong("L_CANT") + TAMANO
'			TAMANO = s.GetLong("L_COSTOU") + TAMANO
'			TAMANO = s.GetLong("L_COSTO_TOT") + TAMANO
'			ESPACIO = ESPACIO - TAMANO
'			For E=0 To ESPACIO -1
'				BLANCO = " " & BLANCO
'			Next
'			printer.WriteLine(BLANCO & s.GETSTRING("PE_CANT") & " X $" & s.GETSTRING("PE_COSTOU") & "   $" & s.GETSTRING("PE_COSTO_TOT") )
'			TAMANO = 0
'			ESPACIO = 21
'			BLANCO = " "
'		Next
'	End If
'	s.Close
'	printer.WriteLine("Total Preventa:   $" & total_cliente)
'	printer.WriteLine("------------VENTA-------------")
'	printer.WriteLine(" ")
'	printer.WriteLine("TOTAL:   $" & total_cliente)
'	printer.WriteLine(" ")
'	printer.WriteLine("----ESTE TICKET NO ES UN -----")
'	printer.WriteLine("--COMPROBANTE FISCAL, SOLO ES-")
'	printer.WriteLine("--------INFORMATIVO-----------")
'	printer.WriteLine("------------------------------")
'	printer.WriteLine(" ")
'	printer.Flush
''	printer.Close
'End Sub

Sub Printer1_Connected (Success As Boolean)
'	If Logger Then Log("Printer1_Connected")
	If Success Then
		ToastMessageShow("Impresora conectada", False)
		Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("MACIMP"))
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP",Starter.mac_impresora))
'		If logger Then LogColor("Impresora conectada", Colors.Green)
'		B_IMP2.Enabled = True
		impresoraConectada = True
	Else
'		Msgbox(Printer1.ConnectedErrorMsg, "Error connecting.") 'ignore
'		ToastMessageShow("Error conectando la impresora", False)
		LogColor("Error conectando la impresora", Colors.Red)
		errorImpresora = errorImpresora + 1
		If errorImpresora > 1 Then
			Starter.MAC_IMPRESORA = "0"
			errorImpresora = 0
		End If
	End If
End Sub

Sub Printer1_Error
	Log("error printer")
End Sub

Sub Printer_Connected (Success As Boolean)
	If Success Then
'		B_IMP.Enabled = True
'		PASA_IMP = "1"
	Else
'		B_IMP.Enabled = False
		If Msgbox2("", "Printer Error","Reprint","Cancel","",Null) = DialogResponse.POSITIVE Then 'ignore
			StartPrinter
		End If
	End If
End Sub

Sub StartPrinter
	Dim PairedDevices As Map
	Dim L1 As List
	Dim resimp As Int
	ToastMessageShow("Printing.....",True)
	PairedDevices.Initialize
	Try
		PairedDevices = cmp20.GetPairedDevices
	Catch
		Msgbox("Getting Paired Devices","Printer Error") 'ignore
		printer.Close
		cmp20.Disconnect
	End Try

	If PairedDevices.Size = 0 Then
		Msgbox("Error Connecting to Printer - Printer Not Found","") 'ignore
		Return
	End If

	If PairedDevices.Size = 1 Then
		Try
			cmp20.Connect(PairedDevices.Get(PairedDevices.GetKeyAt(0)))
		Catch
			Msgbox("Connecting","Printer Error") 'ignore
			printer.Close
			cmp20.Disconnect
		End Try
	Else
		L1.Initialize
		For i = 0 To PairedDevices.Size - 1
			L1.Add(PairedDevices.GetKeyAt(i))
		Next
		resimp = InputList(L1, "Choose device", -1) 'ignore
		If resimp <> DialogResponse.CANCEL Then
			cmp20.Connect(PairedDevices.Get(L1.Get(resimp)))
		End If
	End If
End Sub

Sub B_GUARDA_C_Click
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c=B4XPages.MainPage.skmt.ExecQuery("Select CUENTA from cuentaa")
	c.Position=0
	clie_id = c.GetString("CUENTA")
	c.Close
	c=B4XPages.MainPage.skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	c.Close
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?) ", Array As Object ("4",.01 , .01, 2, "KNORR RINDE MAS 70 GR", "GUNA2",la_cuenta.TEXT, sDate & sTime, usuario,LA_RUTA))
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO HIST_FACE(HFCLIENTE, HFALIAS,HFRUTA,HFALMACEN) VALUES (?,?,?,?) ", Array As Object(la_cuenta.Text, I_COMPRA.Text,LA_RUTA,ALMACEN))
	Panel1.Visible = False
	b_like.Visible = True
	Tar.Visible = True
	Tels.Visible = True
	gest.Visible = True
	Dim future As Cursor = B4XPages.MainPage.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("VENTAFUTURA"))
	If future.RowCount > 0 Then
		future.Position = 0
		If future.GetInt("CAT_VA_VALOR") = 1 Then
			b_preventa2.Visible = True
		Else If future.GetInt("CAT_VA_VALOR") = 0 Then
			b_preventa2.Visible = False
		End If
	End If
	b_like.Visible = False
	Guardar.Visible = True
End Sub

Sub b_venta_Click
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
'	s=B4XPages.MainPage.skmt.ExecQuery("select COUNT(*) AS CUANTOS from HIST_ENCUESTA where HE_CLIE In (Select cuenta from cuentaa)")
'	s.Position= 0
'	If s.GetString("CUANTOS") = 0 Then
'		c=B4XPages.MainPage.skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String("CUESTIONARIO"))
'		c.Position =0
'		If c.GetString("CAT_VA_VALOR") = "2" Then
'			res =  Msgbox2("El cliente maneja CAZARES ?","CAZARES", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'Ignore
'			If res = DialogResponse.POSITIVE Then
'				B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text, "SI",sDate & sTime,"TIENE"))
'				Panel1.Visible =True
'				I_COMPRA.Text = ""
'				BT_QR.Visible= False
'			Else
'				B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text, "NO",sDate & sTime,"TIENE"))
'				B4XPages.MainPage.tipo_venta = "VENTA"
'				B4XPages.ShowPage("Productos")
'			End If
'		Else
'			B4XPages.MainPage.tipo_venta = "VENTA"
'			B4XPages.ShowPage("Productos")
'		End If
'		c.Close
'	Else
'		B4XPages.MainPage.tipo_venta = "VENTA"
'		B4XPages.ShowPage("Productos")
'	End If
'	s.Close
End Sub

Sub B_E_NEXT_Click
	If E_RES_E.Text <> "" Then
		B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO) VALUES (?,?,?,?)", Array As Object(la_cuenta.Text, E_RES_E.Text,sDate & sTime,"DONDE"))
		Panel2.Visible = False
		B4XPages.ShowPage("Productos")
	Else
		Msgbox("SIN RESPUESTA","AVISO") 'Ignore
	End If
End Sub

Sub RB1_CheckedChange(Checked As Boolean)
	If RB1.Checked = True Then
		E_RES_E.Text = "CENTRAL DE ABASTOS"
	End If
End Sub

Sub RB2_CheckedChange(Checked As Boolean)
	If RB2.Checked = True Then
		E_RES_E.Text = "AUTOSERVICIO"
	End If
End Sub

Sub RB3_CheckedChange(Checked As Boolean)
	If RB3.Checked = True Then
		E_RES_E.Text = "CLUB DE PRECIO"
	End If
End Sub

Sub RB4_CheckedChange(Checked As Boolean)
	If RB4.Checked = True Then
		E_RES_E.Text = "DIRECTO PEDEGREE"
	End If
End Sub

Sub b_like_Click
	Panel1.Visible = True
	b_like.Visible = False
	Tar.Visible = False
	Tels.Visible = False
	gest.Visible = False ' : ToastMessageShow("bbbb", False)
	b_venta.Visible = False
	Guardar.Visible = False
End Sub

Sub B_GPS_Click
	Dim result As Int
	result = Msgbox2("Esta seguro de cambiar las coordenadas de este cliente", "Aviso GPS", "SI", "", "NO", LoadBitmap(File.DirAssets, "alerta.jpg")) 'Ignore
	If result = DialogResponse.Positive Then
		B4XPages.MainPage.skmt.ExecNonQuery2("UPDATE kmt_info3 SET CAT_CL_LAT = ?, CAT_CL_LONG = ? where CAT_CL_CODIGO In (Select cuenta from cuentaa)", Array As Object(B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
		B4XPage_Appear
	End If
End Sub

Private Sub p_cliente_Click
	'Nada aqui, solo esta para que los clics no se pasen hacia atras.
End Sub

Private Sub Panel5_Click
	
End Sub

' P2 M1

Private Sub RB1_E1_CheckedChange(Checked As Boolean)
	Log($"RB1 Clicked - chk:${Sender.As(RadioButton).Checked}"$)
	encuentasmapa.Put("P1", Sender.As(RadioButton).text)
	encuentasmapa.Remove("P2")
	Panel7.Visible = False
	RadioButton17.Checked = False
	RadioButton16.Checked = False
	RadioButton15.Checked = False
	encuentasmapa.Remove("P2")
	Log(encuentasmapa)
End Sub

Private Sub RB2_E1_CheckedChange(Checked As Boolean)
	Log($"RB2 Clicked - chk:${Sender.As(RadioButton).Checked}"$)
	encuentasmapa.Put("P1", Sender.As(RadioButton).text)
	RadioButton17.Checked = False
	encuentasmapa.Remove("P2")
	RadioButton17.Checked = False
	RadioButton16.Checked = False
	RadioButton15.Checked = False
	Panel7.Visible = False
	encuentasmapa.Remove("P2")
	Log(encuentasmapa)
End Sub

Private Sub RB3_E1_CheckedChange(Checked As Boolean)
	Log($"RB3 Clicked - chk:${Sender.As(RadioButton).Checked}"$)
	encuentasmapa.Put("P1", Sender.As(RadioButton).text)

	Panel7.Visible = True
	Log(encuentasmapa)
End Sub

' FIN P2 M1

' p2_1 m1
Private Sub RadioButton17_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P2", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton16_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P2", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton15_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P2", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub
' fin p2_1 m1

'PREGUNTA 1 MODULO 1

Private Sub RadioButton1_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P3", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton2_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P3", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton3_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P3", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton4_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P3", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

' FIN PREGUNTA 1 MODULO 1

' P3 M1
Private Sub RadioButton5_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P4", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton6_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P4", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton7_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P4", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton8_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P4", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton9_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P4", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

' FIN P3 M1

'P4 M1

Private Sub RadioButton10_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P5", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton11_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P5", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton12_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P5", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton13_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P5", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

Private Sub RadioButton14_CheckedChange(Checked As Boolean)
	encuentasmapa.Put("P5", Sender.As(RadioButton).text)
	Log(encuentasmapa)
End Sub

' FIN P4 M1

Private Sub CheckBox1_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox1.Text
	If CheckBox2.Checked Then textemp = textemp & ", " & CheckBox2.Text
	If CheckBox3.Checked Then textemp = textemp & ", " & CheckBox3.Text
	If CheckBox4.Checked Then textemp = textemp & ", " & CheckBox4.Text
	If CheckBox5.Checked Then textemp = textemp & ", " & CheckBox5.Text
	If CheckBox6.Checked Then textemp = textemp & ", " & CheckBox6.Text
	If CheckBox7.Checked Then textemp = textemp & ", " & CheckBox7.Text
	If CheckBox8.Checked Then textemp = textemp & ", " & CheckBox8.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub CheckBox2_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox2.Text
	If CheckBox1.Checked Then textemp = textemp & ", " & CheckBox1.Text
	If CheckBox3.Checked Then textemp = textemp & ", " & CheckBox3.Text
	If CheckBox4.Checked Then textemp = textemp & ", " & CheckBox4.Text
	If CheckBox5.Checked Then textemp = textemp & ", " & CheckBox5.Text
	If CheckBox6.Checked Then textemp = textemp & ", " & CheckBox6.Text
	If CheckBox7.Checked Then textemp = textemp & ", " & CheckBox7.Text
	If CheckBox8.Checked Then textemp = textemp & ", " & CheckBox8.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub CheckBox3_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox3.Text
	If CheckBox1.Checked Then textemp = textemp & ", " & CheckBox1.Text
	If CheckBox2.Checked Then textemp = textemp & ", " & CheckBox2.Text
	If CheckBox4.Checked Then textemp = textemp & ", " & CheckBox4.Text
	If CheckBox5.Checked Then textemp = textemp & ", " & CheckBox5.Text
	If CheckBox6.Checked Then textemp = textemp & ", " & CheckBox6.Text
	If CheckBox7.Checked Then textemp = textemp & ", " & CheckBox7.Text
	If CheckBox8.Checked Then textemp = textemp & ", " & CheckBox8.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub CheckBox4_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox4.Text
	If CheckBox1.Checked Then textemp = textemp & ", " & CheckBox1.Text
	If CheckBox2.Checked Then textemp = textemp & ", " & CheckBox2.Text
	If CheckBox3.Checked Then textemp = textemp & ", " & CheckBox3.Text
	If CheckBox5.Checked Then textemp = textemp & ", " & CheckBox5.Text
	If CheckBox6.Checked Then textemp = textemp & ", " & CheckBox6.Text
	If CheckBox7.Checked Then textemp = textemp & ", " & CheckBox7.Text
	If CheckBox8.Checked Then textemp = textemp & ", " & CheckBox8.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub CheckBox5_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox5.Text
	If CheckBox1.Checked Then textemp = textemp & ", " & CheckBox1.Text
	If CheckBox2.Checked Then textemp = textemp & ", " & CheckBox2.Text
	If CheckBox3.Checked Then textemp = textemp & ", " & CheckBox3.Text
	If CheckBox4.Checked Then textemp = textemp & ", " & CheckBox4.Text
	If CheckBox6.Checked Then textemp = textemp & ", " & CheckBox6.Text
	If CheckBox7.Checked Then textemp = textemp & ", " & CheckBox7.Text
	If CheckBox8.Checked Then textemp = textemp & ", " & CheckBox8.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub CheckBox6_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox6.Text
	If CheckBox1.Checked Then textemp = textemp & ", " & CheckBox1.Text
	If CheckBox2.Checked Then textemp = textemp & ", " & CheckBox2.Text
	If CheckBox3.Checked Then textemp = textemp & ", " & CheckBox3.Text
	If CheckBox4.Checked Then textemp = textemp & ", " & CheckBox4.Text
	If CheckBox5.Checked Then textemp = textemp & ", " & CheckBox5.Text
	If CheckBox7.Checked Then textemp = textemp & ", " & CheckBox7.Text
	If CheckBox8.Checked Then textemp = textemp & ", " & CheckBox8.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub CheckBox7_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox7.Text
	If CheckBox1.Checked Then textemp = textemp & ", " & CheckBox1.Text
	If CheckBox2.Checked Then textemp = textemp & ", " & CheckBox2.Text
	If CheckBox3.Checked Then textemp = textemp & ", " & CheckBox3.Text
	If CheckBox4.Checked Then textemp = textemp & ", " & CheckBox4.Text
	If CheckBox5.Checked Then textemp = textemp & ", " & CheckBox5.Text
	If CheckBox6.Checked Then textemp = textemp & ", " & CheckBox6.Text
	If CheckBox8.Checked Then textemp = textemp & ", " & CheckBox8.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub CheckBox8_CheckedChange(Checked As Boolean)
	Dim textemp As String =""
	textemp = CheckBox8.Text
	If CheckBox1.Checked Then textemp = textemp & ", " & CheckBox1.Text
	If CheckBox2.Checked Then textemp = textemp & ", " & CheckBox2.Text
	If CheckBox3.Checked Then textemp = textemp & ", " & CheckBox3.Text
	If CheckBox4.Checked Then textemp = textemp & ", " & CheckBox4.Text
	If CheckBox5.Checked Then textemp = textemp & ", " & CheckBox5.Text
	If CheckBox6.Checked Then textemp = textemp & ", " & CheckBox6.Text
	If CheckBox7.Checked Then textemp = textemp & ", " & CheckBox7.Text
	encuentasmapa.Put("P9", textemp)
	Log(encuentasmapa)
End Sub

Private Sub B_guardaencuesta_m2_Click
	P3_M2 = ""
	P6_M2 = ""
	P4_M2 = ""
	
	PASA = "1"
	If et_p1_m2.Text = "" Then PASA = "0"
	If et_p2_m2.Text = "" Then PASA = "0"
	P4_M2 = ""
	If rd1_p4_m2.Checked Then P4_M2 = "ALTO"
	If rd2_p4_m2.Checked Then P4_M2 = "MEDIO"
	If rd3_p4_m2.Checked Then P4_M2 = "BAJO"
	
	If P4_M2 = "" Then PASA = "0"
	
	P6_M2 = ""
	If RB1_P6_M2.Checked Then P6_M2 = "LUNES"
	If RB2_P6_M2.Checked Then P6_M2 = "MARTES"
	If RB3_P6_M2.Checked Then P6_M2 = "MIERCOLES"
	If RB4_P6_M2.Checked Then P6_M2 = "JUEVES"
	If RB5_P6_M2.Checked Then P6_M2 = "VIERNES"
	If RB6_P6_M2.Checked Then P6_M2 = "SABADO"
	If RB7_P6_M2.Checked Then P6_M2 = "DOMINGO"
	
	If P6_M2 = "" Then PASA = "0"
	
'	P3_M2 = CB1_P3_M2.Checked & "," & CB2_P3_M2.Checked & "," & CB3_P3_M2.Checked & "," & CB4_P3_M2.Checked & "," & CB5_P3_M2.Checked & "," & CB6_P3_M2.Checked & "," & RB1_P3_M2.Checked & "," & RB2_P3_M2.Checked & "," & RB3_P3_M2.Checked& "," & ET_P3_M2.TEXT & "," & CB1_P4_M2.Checked  & "," & CB2_P4_M2.Checked  & "," & CB3_P4_M2.Checked  & "," & CB4_P4_M2.Checked
	If  CB1_P3_M2.Checked = False And  CB2_P3_M2.Checked = False And  CB3_P3_M2.Checked = False And CB4_P3_M2.Checked = False And  CB5_P3_M2.Checked = False And CB6_P3_M2.Checked = False And RB1_P3_M2.Checked = False And RB2_P3_M2.Checked = False And RB3_P3_M2.Checked = False And ET_P3_M2.TEXT = False And CB1_P4_M2.Checked  = False And CB2_P4_M2.Checked  = False And CB3_P4_M2.Checked  = False And CB4_P4_M2.Checked = False Then PASA = "0"
	If et_p5_m2.Text = "" Then PASA = "0"
	Log(textemp2)
	If textemp2 <> "" And textemp2.SubString2(0,2) = ", " Then textemp2 = textemp2.SubString(2)
	Log(textemp2)
	P3_M2 = textemp2
	If RB2_P4_M2.Checked  Then
		P3_M2 = P3_M2 &"|" & "NO"
		
	Else if RB1_P4_M2.Checked Then
		P3_M2 = P3_M2 &"|" & "SI"
		If ET_P3_M2.Text = "" Then
			If RB1_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Rappi"
			If RB2_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Coca Cola"
			If RB3_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Modelo"
			If RB4_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Rabbit"
		Else If ET_P3_M2.Text <> "" Then
			If RB1_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Rappi"
			If RB2_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Coca Cola"
			If RB3_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Modelo"
			If RB4_P3_M2.Checked Then P3_M2 = P3_M2 &"|" & "Rabbit"
			P3_M2 = P3_M2 &", " & ET_P3_M2.Text
		End If
	End If
	If textemp3 <> "" And textemp3.SubString2(0,2) = ", " Then textemp3 = textemp3.SubString(2)
	
	P3_M2 = P3_M2 &"|" & textemp3
	
	If P3_M2 <> "" And P3_M2.SubString2(0,2) = ", " Then P3_M2 = P3_M2.SubString(2)
	LogColor(P3_M2,Colors.BlUE)
	If PASA = "1" Then
		skmt.ExecNonQuery2("INSERT INTO ENCUESTA_MODULO2 (CLIENTE, ALMACEN,P1, P2, P3, P4, P5, P6) VALUES (?,?,?,?,?,?,?,?)", Array As Object(Subs.traeCliente, ALMACEN,et_p1_m2.Text,et_p2_m2.Text,P3_M2,P4_M2,et_p5_m2.Text,P6_M2 ))
		SV_ENCUESTA.Visible = False
		p_cliente.Visible = True
		et_p1_m2.Text = ""
		et_p2_m2.TEXT = ""
		RB7_P6_M2.Checked = False
		RB6_P6_M2.Checked = False
		RB5_P6_M2.Checked = False
		RB4_P6_M2.Checked = False
		RB3_P6_M2.Checked = False
		RB2_P6_M2.Checked = False
		RB1_P6_M2.Checked = False
		et_p5_m2.Text = ""
		rd3_p4_m2.Checked = False
		rd2_p4_m2.Checked = False
		rd1_p4_m2.Checked = False
		RB1_P3_M2.Checked = False
		RB2_P3_M2.Checked = False
		RB3_P3_M2.Checked = False
		RB4_P3_M2.Checked = False
	
		CB1_P3_M2.Checked = False
		CB2_P3_M2.Checked = False
		CB3_P3_M2.Checked = False
		CB4_P3_M2.Checked = False
		CB5_P3_M2.Checked = False
		CB6_P3_M2.Checked = False
	
		ET_P3_M2.Text = ""
		P3_M2 = ""
		P4_M2 = ""
		P6_M2 = ""
	
		Panel7_M2.Visible = False
	
'	B4XPages.MainPage.tipo_venta = "PREVENTA"
'	B4XPages.ShowPage("productos")

		If ENCUESTA > 2 Then
			If p_m2.IsInitialized And p_m2.Visible Then
				p_m2.Visible = False
			Else
							
			End If
			p_pregunta1.Visible = False
			p_cliente.Visible = False
			SV_ENCUESTA.Visible = True
			SV_ENCUESTA.Panel.LoadLayout("ENCUESSTA_M3")
			p_m3.Width = Root.Width * 0.94
			SV_ENCUESTA.Panel.Height = p_m3.Height + 60
			'35,36,45,46,47,54,64,65,71,3,25,27,38
			If  Subs.traeAlmacen  = 1  Or  Subs.traeAlmacen  = 2  Or  Subs.traeAlmacen  = 4 Or  Subs.traeAlmacen  = 5  Or  Subs.traeAlmacen  =35  Or  Subs.traeAlmacen  =36  Or  Subs.traeAlmacen  =45  Or  Subs.traeAlmacen  =46  Or  Subs.traeAlmacen  =47  Or  Subs.traeAlmacen  =54  Or  Subs.traeAlmacen  =64  Or  Subs.traeAlmacen  =65  Or  Subs.traeAlmacen  =71  Or  Subs.traeAlmacen  =3  Or  Subs.traeAlmacen  =25  Or  Subs.traeAlmacen  =27  Or  Subs.traeAlmacen  =38 Then
				CB1_P6_M3.Text = "GARIS"
				CB2_P6_M3.Text = "SAHUAYO"
				CB3_P6_M3.Text = "ZORRO"
				CB4_P6_M3.Text = "ESCORPION"
				CB5_P6_M3.Text = "RABBIT"
				CB6_P6_M3.Text = "SAMS"
		
			else If  Subs.traeAlmacen = 12  Then '
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "ZETA"
				CB3_P6_M3.Text = "SAHUAYO"
				CB4_P6_M3.Text = "DUERO"
				CB5_P6_M3.Text = "HUGOSS"
				CB6_P6_M3.Text = "ZORRO"
			else If  Subs.traeAlmacen = 13  Then '
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "ZETA"
				CB3_P6_M3.Text = "SAHUAYO"
				CB4_P6_M3.Text = "SCORPION"
				CB5_P6_M3.Text = "ZORRO"
				CB6_P6_M3.Text = "GARIS"
			else If  Subs.traeAlmacen = 14   Or  Subs.traeAlmacen  =69  Or  Subs.traeAlmacen  =37 Then '69 -37
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "ZETA"
				CB3_P6_M3.Text = "SAHUAYO"
				CB4_P6_M3.Text = "DUERO"
				CB5_P6_M3.Text = "RIVERA/GRAN BODEGA"
				CB6_P6_M3.Text = "ZORRO"
			else If  Subs.traeAlmacen = 16  Or  Subs.traeAlmacen  =70 Then '70
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "ZETA"
				CB3_P6_M3.Text = "SAHUAYO"
				CB4_P6_M3.Text = "DUERO"
				CB5_P6_M3.Text = "RIVERA/GRAN BODEGA"
				CB6_P6_M3.Text = "SAMS"
			else If  Subs.traeAlmacen = 17  Then '
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "SAHUAYO"
				CB3_P6_M3.Text = ""
				CB4_P6_M3.Text = ""
				CB5_P6_M3.Text = ""
				CB6_P6_M3.Text = ""
			else If  Subs.traeAlmacen = 29  Or  Subs.traeAlmacen  =31 Then '31
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "ZETA"
				CB3_P6_M3.Text = "SAHUAYO"
				CB4_P6_M3.Text = "DUERO"
				CB5_P6_M3.Text = "SAMS"
				CB6_P6_M3.Text = "RIVERA/GRAN BODEGA"
			else If  Subs.traeAlmacen = 32  Or  Subs.traeAlmacen  =33 Then '33
				CB1_P6_M3.Text = "MAS BODEGA"
				CB2_P6_M3.Text = "SAHUAYO"
				CB3_P6_M3.Text = "TREVIÑO"
				CB4_P6_M3.Text = "HUGOSS"
				CB5_P6_M3.Text = "RABBIT"
				CB6_P6_M3.Text = "SAMS"
			else If  Subs.traeAlmacen = 66  Or  Subs.traeAlmacen  =67 Then '67
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "ZETA"
				CB3_P6_M3.Text = "SAHUAYO"
				CB4_P6_M3.Text = "DUERO"
				CB5_P6_M3.Text = "SCORPION"
				CB6_P6_M3.Text = "SAMS"
		
			else If  Subs.traeAlmacen = 22  Or  Subs.traeAlmacen  =34 Then '34
				CB1_P6_M3.Text = "DECASA"
				CB2_P6_M3.Text = "ZETA"
				CB3_P6_M3.Text = "SAHUAYO"
				CB4_P6_M3.Text = "MERZA/DUERO"
				CB5_P6_M3.Text = "HUGOSS"
			End If
		Else
			p_pregunta1.Visible = False
			SV_ENCUESTA.Visible = False
			p_cliente.Visible = True
'			tipo_venta = "PREVENTA"
			B4XPages.ShowPage("productos")
			MsgboxAsync("Encuesta guardada","")
		End If
	Else
		Msgbox("FAVOR DE CONTESTAR LA ENCUESTA","AVISO")
	End If
End Sub

Private Sub CB6_P3_M2_CheckedChange(Checked As Boolean)
	If CB6_P3_M2.Checked = True Then
		Panel7_M2.Visible = True
	Else
		Panel7_M2.Visible = False
	End If
	
	
End Sub

Private Sub B_guardaencuesta_m3_Click
	
	PASA = "1"
'	textemp4 = ""
'	textemp5 = ""
'	textemp6 = ""
'	textemp7 = ""
'	textemp8 = ""
	Private P3_M3 As String = ""
	Private P4_M3 As String = ""
	Private P5_M3 As String = ""
	Private P6_M3 As String = ""
	Private P7_M3 As String = ""
	Private P8_M3 As String = ""
	Private P9_M3 As String = ""
	
	
'	If et_p1_m3.Text = "" Then PASA = "0"
'	If et_p2_m3.Text = "" Then PASA = "0"
	
	If rd1_p5_m3.Checked Then P5_M3 = "SI"
	If rd2_p5_m3.Checked Then P5_M3 = "NO"
	
	If RB1_P9_M3.Checked Then P9_M3 = "DIARIO"
	If RB2_P9_M3.Checked Then P9_M3 = "BISEMANAL"
	If RB3_P9_M3.Checked Then P9_M3 = "SEMANAL"
	If RB4_P9_M3.Checked Then P9_M3 = "QUINCENAL"
	If RB5_P9_M3.Checked Then P9_M3 = "MENSUAL"
	If P9_M3 = "" Then PASA = "0"
	If P5_M3 = "" Then PASA = "0"
	
'	P3_M3 = CB1_P3_M3.Checked & "," & CB2_P3_M3.Checked & "," & CB3_P3_M3.Checked & "," & CB4_P3_M3.Checked & "," & CB5_P3_M3.Checked
	If CB1_P3_M3.Checked = False And  CB2_P3_M3.Checked = False And CB3_P3_M3.Checked = False And CB4_P3_M3.Checked = False And CB5_P3_M3.Checked = False Then PASA = "0"
'	P4_M3 = CB1_P4_M3.Checked & "," & CB2_P4_M3.Checked & "," & CB3_P4_M3.Checked & "," & CB4_P4_M3.Checked & "," & CB5_P4_M3.Checked
	If  CB1_P4_M3.Checked  = False And  CB2_P4_M3.Checked  = False And  CB3_P4_M3.Checked  = False And  CB4_P4_M3.Checked  = False And  CB5_P4_M3.Checked = False Then PASA = "0"
	
'	P6_M3 = CB1_P6_M3.Checked & "," & CB2_P6_M3.Checked & "," & CB3_P6_M3.Checked & "," & CB4_P6_M3.Checked & "," & CB5_P6_M3.Checked & "," & CB6_P6_M3.Checked  & "," & ET_P6_M3.TEXT
	
'	P7_M3 = CB1_P7_M3.Checked & "," & CB2_P7_M3.Checked & "," & CB3_P7_M3.Checked & "," & CB4_P7_M3.Checked
	If CB1_P7_M3.Checked  = False And  CB2_P7_M3.Checked  = False And  CB3_P7_M3.Checked  = False And  CB4_P7_M3.Checked = False Then PASA = "0"
	
'	P8_M3 = CB1_P8_M3.Checked & "," & CB2_P8_M3.Checked & "," & CB3_P8_M3.Checked & "," & CB4_P8_M3.Checked
	If CB1_P8_M3.Checked = False And  CB2_P8_M3.Checked = False And  CB3_P8_M3.Checked = False And  CB4_P8_M3.Checked = False Then PASA = "0"
	If rb1_m3_p1.Checked Then P3_M3 = "7 A 9"
	If RB2_M3_P1.Checked Then P3_M3 = "9 A 11"
	If RB3_M3_P1.Checked Then P3_M3 = "11 A 13"
	If RB4_M3_P1.Checked Then P3_M3 = "13 +"
	
	If RB1_M3_P2.Checked Then P4_M3 = "2 A 4"
	If RB2_M3_P2.Checked Then P4_M3 = "4 A 6"
	If RB3_M3_P2.Checked Then P4_M3 = "6 A 8"
	If RB4_M3_P2.Checked Then P4_M3 = "8 +"
	
	If CB5_P4_M3.Checked  = True And ( CB2_P4_M3.Checked = True Or  CB3_P4_M3.Checked = True Or  CB4_P4_M3.Checked = True Or CB1_P4_M3.Checked = True ) Then
		PASA = "0"
		CB5_P4_M3.Checked = False
		CB2_P4_M3.Checked = False
		CB3_P4_M3.Checked = False
		CB4_P4_M3.Checked = False
		CB1_P4_M3.Checked = False
	End If
	
	
	If PASA = "1" Then
		If rb1_m3_p1.Checked Then P3_M3 = "7 A 9"
		If RB2_M3_P1.Checked Then P3_M3 = "9 A 11"
		If RB3_M3_P1.Checked Then P3_M3 = "11 A 13"
		If RB4_M3_P1.Checked Then P3_M3 = "13 +"
	
		If RB1_M3_P2.Checked Then P4_M3 = "2 A 4"
		If RB2_M3_P2.Checked Then P4_M3 = "4 A 6"
		If RB3_M3_P2.Checked Then P4_M3 = "6 A 8"
		If RB4_M3_P2.Checked Then P4_M3 = "8 +"
		
		If ET_P6_M3.Text <> "" Then
			textemp6 = textemp6 & ", " & ET_P6_M3.Text
		End If
		
		If textemp4 <> "" And textemp4.SubString2(0,2) = ", " Then textemp4 = textemp4.SubString(2)
		If textemp5 <> "" And textemp5.SubString2(0,2) = ", " Then textemp5 = textemp5.SubString(2)
		If textemp6 <> "" And textemp6.SubString2(0,2) = ", " Then textemp6 = textemp6.SubString(2)
		If textemp7 <> "" And textemp7.SubString2(0,2) = ", " Then textemp7 = textemp7.SubString(2)
		If textemp8 <> "" And textemp8.SubString2(0,2) = ", " Then textemp8 = textemp8.SubString(2)
'	skmt.ExecNonQuery2("INSERT INTO ENCUESTA_MODULO2 (CLIENTE, ALMACEN,P1, P2, P3, P4, P5, P6) VALUES (?,?,?,?,?,?,?,?)", Array As Object(Subs.traeCliente, ALMACEN,et_p1_m2.Text,et_p2_m2.Text,P3_M2,P4_M2,et_p5_m2.Text,"MODULO_3" ))
	
	
		skmt.ExecNonQuery2("INSERT INTO ENCUESTA_MODULO3 (CLIENTE, ALMACEN,P1, P2, P3, P4, P5, P6,P7,P8,P9,P10,P11) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", Array As Object(Subs.traeCliente, ALMACEN,"x","x",P3_M3,P4_M3,textemp4,textemp5,P5_M3,textemp6,textemp7, textemp8, P9_M3))
		SV_ENCUESTA.Visible = False
		p_cliente.Visible = True
'	B4XPages.MainPage.tipo_venta = "PREVENTA"
'	B4XPages.ShowPage("productos")
		If ENCUESTA > 3 Then
			If p_m3.IsInitialized And p_m3.Visible Then
				p_m3.Visible = False
			Else
							
			End If
			p_pregunta1.Visible = False
			p_cliente.Visible = False
			SV_ENCUESTA.Visible = True
			p_pregunta1.Visible = False
			SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M4")
			p_m4.Width = Root.Width * 0.94
			SV_ENCUESTA.Panel.Height = p_m4.Height + 60
			
			Dim Items2 As List
			Items2.Initialize
			Items2.Add("Selecciona una opcion")
			Items2.Add("Propio")
			Items2.Add("Rentado")
			cb_p3_m4.SetItems(Items2)
			itemselect2 = "Selecciona una opcion"
	
	
			Dim Items3 As List
			Items3.Initialize
			Items3.Add("Selecciona una opcion")
			Items3.Add("Completamente Surtido")
			Items3.Add("Bien Surtido")
			Items3.Add("Poco Surtido")
			Items3.Add("Muy Poco Surtido")
			Items3.Add("Sin Existencias")
			cb_p4_1_m4.SetItems(Items3)
			itemselect3 = "Selecciona una opcion"
			cb_p4_2_m4.SetItems(Items3)
			itemselect4 = "Selecciona una opcion"
			cb_p4_3_m4.SetItems(Items3)
			itemselect5 = "Selecciona una opcion"
			cb_p4_4_m4.SetItems(Items3)
			itemselect6 = "Selecciona una opcion"
			cb_p4_5_m4.SetItems(Items3)
			itemselect7 = "Selecciona una opcion"
		Else
			p_pregunta1.Visible = False
			SV_ENCUESTA.Visible = False
			p_cliente.Visible = True
'			tipo_venta = "PREVENTA"
			B4XPages.ShowPage("productos")
			MsgboxAsync("Encuesta guardada","")
		End If
	Else
		Msgbox("FAVOR DE CONTESTAR LA ENCUESTA","AVISO")
	End If
End Sub

Private Sub B_guardaencuesta_m4_Click
	
	PASA = "1"
	
	If itemselect2 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect3 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect4 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect5 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect6 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect7 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If et_p1_m4.Text.Length  < 2 Then
		
		et_p1_m4.Text = ""
		PASA = "0"
	End If
	If PASA = "1" Then
		skmt.ExecNonQuery2("INSERT INTO ENCUESTA_MODULO4 (CLIENTE, ALMACEN,P1, P2, P3, P4, P5, P6, P7, P8) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(Subs.traeCliente, ALMACEN,et_p1_m4.Text,et_p2_m4.Text,itemselect2,itemselect3,itemselect4,itemselect5,itemselect6,itemselect7))
		SV_ENCUESTA.Visible = False
		p_cliente.Visible = True
'	
		If ENCUESTA > 4 Then
			If p_m4.IsInitialized And p_m4.Visible Then
				p_m4.Visible = False
			Else
							
			End If
			p_cliente.Visible = False
			SV_ENCUESTA.Visible = True
			p_pregunta1.Visible = False
			SV_ENCUESTA.Panel.LoadLayout("ENCUESTA_M5")
			p_modulo5.Width = Root.Width * 0.94
			SV_ENCUESTA.Panel.Height = p_modulo5.Height + 60
	
			Dim Items8 As List
			Items8.Initialize
			Items8.Add("Selecciona una opcion")
			Items8.Add("Completamente Surtido")
			Items8.Add("Bien Surtido")
			Items8.Add("Poco Surtido")
			Items8.Add("Muy Poco Surtido")
			Items8.Add("Sin Existencias")
			cb_p1_m5.SetItems(Items8)
			itemselect8 = "Selecciona una opcion"
			cb_p2_m5.SetItems(Items8)
			itemselect9 = "Selecciona una opcion"
			cb_p3_m5.SetItems(Items8)
			itemselect10 = "Selecciona una opcion"
			cb_p4_m5.SetItems(Items8)
			itemselect11 = "Selecciona una opcion"
			cb_p5_m5.SetItems(Items8)
			itemselect12 = "Selecciona una opcion"
			cb_p6_m5.SetItems(Items8)
			itemselect13 = "Selecciona una opcion"
			cb_p7_m5.SetItems(Items8)
			itemselect14 = "Selecciona una opcion"
			cb_p8_m5.SetItems(Items8)
			itemselect15 = "Selecciona una opcion"
			cb_p9_m5.SetItems(Items8)
			itemselect16 = "Selecciona una opcion"
			MsgboxAsync("Encuesta guardada","")
		Else
			B4XPages.MainPage.tipo_venta = tipo_venta
'			tipo_venta = "PREVENTA"
			p_pregunta1.Visible = False
			SV_ENCUESTA.Visible = False
			p_cliente.Visible = True
			B4XPages.ShowPage("productos")
		End If
	Else
		Msgbox("FAVOR DE CONTESTAR LA ENCUESTA","AVISO")
	End If
	
End Sub

Private Sub B_guardaencuesta_m5_Click
	
	PASA = "1"
	
	If itemselect8 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect9 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect10 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect11 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect12 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect13 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect14 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect15 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	If itemselect16 = "Selecciona una opcion" Then
		PASA = "0"
	End If
	
	If PASA = "1" Then
		skmt.ExecNonQuery2("INSERT INTO ENCUESTA_MODULO5 (CLIENTE, ALMACEN,P1, P2, P3, P4, P5, P6, P7, P8, P9) VALUES (?,?,?,?,?,?,?,?,?,?,?)", Array As Object(Subs.traeCliente, ALMACEN,itemselect8,itemselect9,itemselect10,itemselect11,itemselect12,itemselect13,itemselect14,itemselect15,itemselect16))
		SV_ENCUESTA.Visible = False
		p_cliente.Visible = True
		B4XPages.MainPage.tipo_venta = tipo_venta
		B4XPages.ShowPage("productos")
		MsgboxAsync("Encuesta guardada","")
	Else
		Msgbox("FAVOR DE CONTESTAR LA ENCUESTA","AVISO")
	End If
End Sub


Private Sub B_ACEPTA_GALLINA_Click
	
	
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c=skmt.ExecQuery("Select CUENTA from cuentaa")
	c.Position=0
	clie_id = c.GetString("CUENTA")
	c.Close
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	c.Close
	c=skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	If c.RowCount>0 Then
		C.Position=0
		ALMACEN = C.GetString("ID_ALMACEN")
	End If
	c.Close
	skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?) ", Array As Object ("PRO1771",0 , 0, 1, "1 KNORR SUIZA EXH C/50/22 GR +1 KNORR SUIZA GALLINA $279.00", "PRO1771",la_cuenta.TEXT, sDate & sTime, usuario,LA_RUTA))
	skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?) ", Array As Object ("PRO1771",139.5 , 139.5, 1, "KNORR SUIZA EXH C/50/22 GR", "UNI047",la_cuenta.TEXT, sDate & sTime, usuario,LA_RUTA))
	skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?) ", Array As Object ("PRO1771",139.5 , 139.5, 1, "KNORR SUIZA GALLINA", "UNI860",la_cuenta.TEXT, sDate & sTime, usuario,LA_RUTA))
	
	c=skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	c.Position=0
	skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
	skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps,ALMACEN,LA_RUTA,c.GetString("TOTAL_CLIE_SIN")))
	skmt.ExecNonQuery("UPDATE kmt_info3 set gestion = 2  where CAT_CL_CODIGO In (select cuenta from cuentaa)")

	
	'Panel5.Visible = False
	B_GALLINA.Visible = False
	b_like.Visible = True
	Tar.Visible = True
	Tels.Visible = True
	gest.Visible = True
	'b_venta.Visible = True
	b_like.Visible = False
	Guardar.Visible = True
	P_gallina.Visible = False
End Sub

Private Sub B_CANCELA_GALLINA_Click
	P_gallina.Visible = False
	'Panel5.Visible = False
	B_GALLINA.Visible = False
	b_like.Visible = True
	Tar.Visible = True
	Tels.Visible = True
	gest.Visible = True
	'b_venta.Visible = True
	b_like.Visible = False
	Guardar.Visible = True
'	tipo_venta = "PREVENTA"
'	StartActivity(colonia2)
End Sub

Private Sub B_GALLINA_Click
	P_gallina.Visible = True
	
	B_GALLINA.Visible = False
	b_like.Visible = False
	BT_QR.Visible = False
	'Panel5.Visible = True
	b_like.Visible = False
	Tar.Visible = False
	Tels.Visible = False
	gest.Visible = False ': ToastMessageShow("ccc", False)
	b_venta.Visible = False
	Guardar.Visible = False
	HIST.Visible = False
End Sub

' P5 M1
Private Sub p6_TextChanged (Old As String, New As String)
	If p6.Text.Length  > 2 Then
		Msgbox("Valida tu respuesta, dato no valido1","Aviso")
		p6.Text = ""
	End If
End Sub
' FIN P5 M1

' P6 M1
Private Sub p7_TextChanged (Old As String, New As String)
	If p7.Text.Length  > 2 Then
		Msgbox("Valida tu respuesta, dato no valido2","Aviso")
		p7.Text = ""
	End If
End Sub
' FIN P6 M1

' P7 M1
Private Sub p8_TextChanged (Old As String, New As String)
	If p8.Text.Length  > 2 Then
		
		Msgbox("Valida tu respuesta, dato no valido3","Aviso")
		p8.Text = ""
	End If
End Sub

' FIN P7 M1
''aqui

'Private Sub et_p1_m3_TextChanged (Old As String, New As String)
'	If et_p1_m3.Text.Length  > 2 Or et_p1_m3.Text = 0 Then
'		
'		Msgbox("Valida tu respuesta, dato no valido","Aviso")
'		et_p1_m3.Text = ""
'	End If
'End Sub

'Private Sub et_p2_m3_TextChanged (Old As String, New As String)
'	If et_p2_m3.Text.Length  > 2 Or et_p2_m3.Text = 0 Then
'		
'		Msgbox("Valida tu respuesta, dato no valido","Aviso")
'		et_p2_m3.Text = ""
'		
'	End If
'End Sub

Private Sub et_p1_m2_TextChanged (Old As String, New As String)
	If et_p1_m2.Text.Length  > 2 Or et_p1_m2.Text = 0 Then
		
		Msgbox("Valida tu respuesta, dato no valido","Aviso")
		et_p1_m2.Text = ""
	End If
End Sub

Private Sub et_p2_m2_TextChanged (Old As String, New As String)
	If et_p2_m2.Text.Length  > 2 Or et_p2_m2.Text = 0 Then
		
		Msgbox("Valida tu respuesta, dato no valido","Aviso")
		et_p2_m2.Text = ""
		
	End If
End Sub

Private Sub et_p5_m2_TextChanged (Old As String, New As String)
	If et_p5_m2.Text.Length  > 4 Then
		
		Msgbox("Valida tu respuesta, dato no valido","Aviso")
		et_p5_m2.Text = ""
	End If
End Sub

Private Sub et_p1_m4_TextChanged (Old As String, New As String)
	If et_p1_m4.Text.Length  > 5 Then
		
		Msgbox("Valida tu respuesta, dato no valido","Aviso")
		et_p1_m4.Text = ""
	End If
End Sub


Private Sub RB1_P4_M2_CheckedChange(Checked As Boolean)
	If RB1_P4_M2.Checked = True Then
		Panel7_M2.Visible = True
		panel7_p4_m2.Visible = True
	Else
		Panel7_M2.Visible = False
		panel7_p4_m2.Visible = False
		
	End If
End Sub

Private Sub RB2_P4_M2_CheckedChange(Checked As Boolean)
	If RB2_P4_M2.Checked = True Then
		Panel7_M2.Visible = False
		panel7_p4_m2.Visible = False
		RB1_P3_M2.Checked = False
		RB2_P3_M2.Checked = False
		RB3_P3_M2.Checked = False
		RB4_P3_M2.Checked = False
		ET_P3_M2.Text = ""
		CB1_P4_M2.Checked = False
		CB2_P4_M2.Checked = False
		CB3_P4_M2.Checked = False
		CB4_P4_M2.Checked = False
		textemp3 = ""
	Else
		Panel7_M2.Visible = True
		panel7_p4_m2.Visible = True
		
	End If
End Sub

Private Sub B_GUARDA_CE_PED_Click
	
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	c=skmt.ExecQuery("Select CUENTA from cuentaa")
	c.Position=0
	clie_id = c.GetString("CUENTA")
	c.Close
	c=skmt.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	usuario = c.GetString("USUARIO")
	c.Close
	c=skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	If c.RowCount>0 Then
		C.Position=0
		ALMACEN = C.GetString("ID_ALMACEN")
	End If
	c.Close
	
'	
'	If rdb_ch.Checked = True Then TAMANIO = "CHICA"
'	If rdb_gd.Checked = True Then TAMANIO = "GRANDE"
'	If rdb_md.Checked = True Then TAMANIO = "MEDIANA"
'	If rdb_vt.Checked = True Then TAMANIO = "VENTANITA"
'	
'	If RDB_SI.Checked = True Then ENTRADA = "SI"
'	
'	If RDB_NO.Checked = True Then 
'		ENTRADA = "NO"
'		TAMANIO = "VENTANITA"
'	End If
'	
	'la enecuesta actual
	
	skmt.ExecNonQuery2("INSERT INTO HIST_ENCUESTA_PED_DIST_1(ALMACEN , TIENDA , KP_01  , KP_02  , KP_03  , KP_04  , KP_05  , KP_06  , KP_07  , KP_08  , KP_09  , KP_10  , KP_11  , KP_12  , KP_13  , KP_14  , KP_15  , KP_16  , KP_17  , KP_18  , KP_19  , KP_20  , KG_01  , KG_02  , KG_03  , KG_04  , KG_05  , KG_06  , PK_01  , PK_02  , PK_03  , PK_04  , PK_05  , PK_06  , PK_07  , PK_08) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object(ALMACEN, clie_id,KP_01.Checked,KP_02.Checked,KP_03.Checked,KP_04.Checked,KP_05.Checked,KP_06.Checked,KP_07.Checked,KP_08.Checked,KP_09.Checked,KP_10.Checked,KP_11.Checked,KP_12.Checked,KP_13.Checked,KP_14.Checked,KP_15.Checked,KP_16.Checked,KP_17.Checked,KP_18.Checked,KP_19.Checked,KP_20.Checked,KG_01.Checked,KG_02.Checked,KG_03.Checked,KG_04.Checked,KG_05.Checked,KG_06.Checked,PK_01.Checked,PK_02.Checked,PK_03.Checked,PK_04.Checked,PK_05.Checked,PK_06.Checked,PK_07.Checked,PK_08.Checked ))
	
	skmt.ExecNonQuery2("INSERT INTO HIST_ENCUESTA_PED_DIST_2(ALMACEN , TIENDA , HPG_01  , HPG_02  , HPG_03  , HPG_04  , HPG_05  , HPG_06  , HPG_07  , HPG_08  , HPG_09  , HPG_10  , HC_01  , HC_02  , HC_03  , HC_04  , B_01  , B_02) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object(ALMACEN, clie_id, HPG_01.Checked,HPG_02.Checked,HPG_03.Checked,HPG_04.Checked,HPG_05.Checked,HPG_06.Checked,HPG_07.Checked,HPG_08.Checked,HPG_09.Checked,HPG_10.Checked,HC_01.Checked,HC_02.Checked,HC_03.Checked,HC_04.Checked,B_01.Checked,B_02.Checked))
	
	'la encuesta anterior
	
'	skmt.ExecNonQuery2("INSERT INTO HIST_ENCUESTA_PED_SEG(ALMACEN , TIENDA , TAMANIO , ENTRADA , BULTOSP , BULTOSG) VALUES (?,?,?,?,?,?) ", Array As Object(ALMACEN, clie_id, TAMANIO,ENTRADA, I_COMPRA2.TEXT, I_COMPRA.TEXT))
	
	
	
'	skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA) VALUES(?,?,?,?,?,?,?,?,?,?) ", Array As Object ("4",.01 , .01, 2, "KNORR RINDE MAS 70 GR", "GUNA2",la_cuenta.TEXT, sDate & sTime, usuario,LA_RUTA))
	
'	skmt.ExecNonQuery2("INSERT INTO HIST_FACE(HFCLIENTE, HFALIAS,HFRUTA,HFALMACEN) VALUES (?,?,?,?) ", Array As Object(la_cuenta.Text, I_COMPRA.Text,LA_RUTA,ALMACEN))
	
	'I_COMPRA2.TEXT = ""
	I_COMPRA.TEXT  = ""
	SV_ENCUESTA.Visible = False
	Panel1.Visible = False
'	Panel4.Visible = False
	b_like.Visible = True
	Tar.Visible = True
	Tels.Visible = True
	gest.Visible = True
	'b_venta.Visible = True
	b_like.Visible = False
	Guardar.Visible = True
'	tipo_venta = "PREVENTA"
	B4XPages.ShowPage("productos")
	
End Sub


Private Sub p_modulo5_Click
	
End Sub

Private Sub Panel4_Click
	
End Sub

Private Sub CB1_P3_M2_CheckedChange(Checked As Boolean)
	textemp2 = ""
	If CB1_P3_M2.Checked Then
		textemp2 = CB1_P3_M2.Text
	Else
		textemp2 = ""
	End If
	If CB2_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB2_P3_M2.Text
	If CB3_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB3_P3_M2.Text
	If CB4_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB4_P3_M2.Text
	If CB5_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB5_P3_M2.Text
	Log(textemp2)
End Sub

Private Sub CB2_P3_M2_CheckedChange(Checked As Boolean)
	textemp2 = ""
	If CB2_P3_M2.Checked Then
		textemp2 = CB2_P3_M2.Text
	Else
		textemp2 = ""
	End If
	If CB1_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB1_P3_M2.Text
	If CB3_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB3_P3_M2.Text
	If CB4_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB4_P3_M2.Text
	If CB5_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB5_P3_M2.Text
	Log(textemp2)
End Sub

Private Sub CB3_P3_M2_CheckedChange(Checked As Boolean)
	textemp2 = ""
	If CB3_P3_M2.Checked Then
		textemp2 = CB3_P3_M2.Text
	Else
		textemp2 = ""
	End If
	If CB1_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB1_P3_M2.Text
	If CB2_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB2_P3_M2.Text
	If CB4_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB4_P3_M2.Text
	If CB5_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB5_P3_M2.Text
	Log(textemp2)
End Sub

Private Sub CB4_P3_M2_CheckedChange(Checked As Boolean)
	textemp2 = ""
	If CB4_P3_M2.Checked Then
		textemp2 = CB4_P3_M2.Text
	Else
		textemp2 = ""
	End If
	If CB1_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB1_P3_M2.Text
	If CB2_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB2_P3_M2.Text
	If CB3_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB3_P3_M2.Text
	If CB5_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB5_P3_M2.Text
	Log(textemp2)
End Sub

Private Sub CB5_P3_M2_CheckedChange(Checked As Boolean)
	textemp2 = ""
	If CB5_P3_M2.Checked Then
		textemp2 = CB5_P3_M2.Text
	Else
		textemp2 = ""
	End If
	If CB1_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB1_P3_M2.Text
	If CB2_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB2_P3_M2.Text
	If CB3_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB3_P3_M2.Text
	If CB4_P3_M2.Checked Then textemp2 = textemp2 & ", " & CB4_P3_M2.Text
	Log(textemp2)
End Sub



Private Sub CB1_P4_M2_CheckedChange(Checked As Boolean)
	textemp3 = ""
	If CB1_P4_M2.Checked Then
		textemp3 = CB1_P4_M2.Text
	Else
		textemp3 = ""
	End If
	If CB2_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB2_P4_M2.Text
	If CB3_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB3_P4_M2.Text
	If CB4_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB4_P4_M2.Text
	Log(textemp3)
End Sub

Private Sub CB2_P4_M2_CheckedChange(Checked As Boolean)
	textemp3 = ""
	If CB2_P4_M2.Checked Then
		textemp3 = CB2_P4_M2.Text
	Else
		textemp3 = ""
	End If
	If CB1_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB1_P4_M2.Text
	If CB3_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB3_P4_M2.Text
	If CB4_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB4_P4_M2.Text
	Log(textemp3)
End Sub

Private Sub CB3_P4_M2_CheckedChange(Checked As Boolean)
	textemp3 = ""
	If CB3_P4_M2.Checked Then
		textemp3 = CB3_P4_M2.Text
	Else
		textemp3 = ""
	End If
	If CB1_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB1_P4_M2.Text
	If CB2_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB2_P4_M2.Text
	If CB4_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB4_P4_M2.Text
	Log(textemp3)
End Sub

Private Sub CB4_P4_M2_CheckedChange(Checked As Boolean)
	textemp3 = ""
	If CB4_P4_M2.Checked Then
		textemp3 = CB4_P4_M2.Text
	Else
		textemp3 = ""
	End If
	If CB1_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB1_P4_M2.Text
	If CB2_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB2_P4_M2.Text
	If CB3_P4_M2.Checked Then textemp3 = textemp3 & ", " & CB3_P4_M2.Text
	Log(textemp3)
End Sub




Private Sub CB1_P3_M3_CheckedChange(Checked As Boolean)
	textemp4 = ""
	If CB1_P3_M3.Checked Then
		textemp4 = CB1_P3_M3.Text
	Else
		textemp4 = ""
	End If
	If CB2_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB2_P3_M3.Text
	If CB3_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB3_P3_M3.Text
	If CB4_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB4_P3_M3.Text
	If CB5_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB5_P3_M3.Text
	Log(textemp4)
End Sub

Private Sub CB2_P3_M3_CheckedChange(Checked As Boolean)
	textemp4 = ""
	If CB2_P3_M3.Checked Then
		textemp4 = CB2_P3_M3.Text
	Else
		textemp4 = ""
	End If
	If CB1_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB1_P3_M3.Text
	If CB3_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB3_P3_M3.Text
	If CB4_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB4_P3_M3.Text
	If CB5_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB5_P3_M3.Text
	Log(textemp4)
End Sub

Private Sub CB3_P3_M3_CheckedChange(Checked As Boolean)
	textemp4 = ""
	If CB3_P3_M3.Checked Then
		textemp4 = CB3_P3_M3.Text
	Else
		textemp4 = ""
	End If
	If CB1_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB1_P3_M3.Text
	If CB2_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB2_P3_M3.Text
	If CB4_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB4_P3_M3.Text
	If CB5_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB5_P3_M3.Text
	Log(textemp4)
End Sub

Private Sub CB4_P3_M3_CheckedChange(Checked As Boolean)
	textemp4 = ""
	If CB4_P3_M3.Checked Then
		textemp4 = CB4_P3_M3.Text
	Else
		textemp4 = ""
	End If
	If CB1_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB1_P3_M3.Text
	If CB2_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB2_P3_M3.Text
	If CB3_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB3_P3_M3.Text
	If CB5_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB5_P3_M3.Text
	Log(textemp4)
End Sub

Private Sub CB5_P3_M3_CheckedChange(Checked As Boolean)
	textemp4 = ""
	If CB5_P3_M3.Checked Then
		textemp4 = CB5_P3_M3.Text
	Else
		textemp4 = ""
	End If
	If CB1_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB1_P3_M3.Text
	If CB2_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB2_P3_M3.Text
	If CB3_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB3_P3_M3.Text
	If CB4_P3_M3.Checked Then textemp4 = textemp4 & ", " & CB4_P3_M3.Text
	Log(textemp4)
End Sub



Private Sub CB1_P4_M3_CheckedChange(Checked As Boolean)
	textemp5 = ""
	CB5_P4_M3.Checked = False
	If CB1_P4_M3.Checked Then
		textemp5 = CB1_P4_M3.Text
	Else
		textemp5 = ""
	End If
	If CB2_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB2_P4_M3.Text
	If CB3_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB3_P4_M3.Text
	If CB4_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB4_P4_M3.Text
	If CB5_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB5_P4_M3.Text
	Log(textemp5)
End Sub

Private Sub CB2_P4_M3_CheckedChange(Checked As Boolean)
	textemp5 = ""
	CB5_P4_M3.Checked = False
	If CB2_P4_M3.Checked Then
		textemp5 = CB2_P4_M3.Text
	Else
		textemp5 = ""
	End If
	If CB1_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB1_P4_M3.Text
	If CB3_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB3_P4_M3.Text
	If CB4_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB4_P4_M3.Text
	If CB5_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB5_P4_M3.Text
	Log(textemp5)
End Sub

Private Sub CB3_P4_M3_CheckedChange(Checked As Boolean)
	textemp5 = ""
	CB5_P4_M3.Checked = False
	If CB3_P4_M3.Checked Then
		textemp5 = CB3_P4_M3.Text
	Else
		textemp5 = ""
	End If
	If CB1_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB1_P4_M3.Text
	If CB2_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB2_P4_M3.Text
	If CB4_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB4_P4_M3.Text
	If CB5_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB5_P4_M3.Text
	Log(textemp5)
End Sub

Private Sub CB4_P4_M3_CheckedChange(Checked As Boolean)
	textemp5 = ""
	CB5_P4_M3.Checked = False
	If CB4_P4_M3.Checked Then
		textemp5 = CB4_P4_M3.Text
	Else
		textemp5 = ""
	End If
	If CB1_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB1_P4_M3.Text
	If CB2_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB2_P4_M3.Text
	If CB3_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB3_P4_M3.Text
	If CB5_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB5_P4_M3.Text
	Log(textemp5)
End Sub

Private Sub CB5_P4_M3_CheckedChange(Checked As Boolean)
	textemp5 = ""
	CB1_P4_M3.Checked = False
	CB2_P4_M3.Checked = False
	CB3_P4_M3.Checked = False
	CB4_P4_M3.Checked = False
	If CB5_P4_M3.Checked Then
		textemp5 = CB5_P4_M3.Text
	Else
		textemp5 = ""
	End If
	If CB1_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB1_P4_M3.Text
	If CB2_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB2_P4_M3.Text
	If CB3_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB3_P4_M3.Text
	If CB4_P4_M3.Checked Then textemp5 = textemp5 & ", " & CB4_P4_M3.Text
	Log(textemp5)
End Sub




Private Sub CB1_P6_M3_CheckedChange(Checked As Boolean)
	textemp6 = ""
	If CB1_P6_M3.Checked Then
		textemp6 = CB1_P6_M3.Text
	Else
		textemp6 = ""
	End If
	If CB2_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB2_P6_M3.Text
	If CB3_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB3_P6_M3.Text
	If CB4_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB4_P6_M3.Text
	If CB5_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB5_P6_M3.Text
	If CB6_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB6_P6_M3.Text
	If CB7_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB7_P6_M3.Text
	Log(textemp6)
End Sub

Private Sub CB2_P6_M3_CheckedChange(Checked As Boolean)
	textemp6 = ""
	If CB2_P6_M3.Checked Then
		textemp6 = CB2_P6_M3.Text
	Else
		textemp6 = ""
	End If
	If CB1_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB1_P6_M3.Text
	If CB3_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB3_P6_M3.Text
	If CB4_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB4_P6_M3.Text
	If CB5_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB5_P6_M3.Text
	If CB6_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB6_P6_M3.Text
	If CB7_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB7_P6_M3.Text
	Log(textemp6)
End Sub

Private Sub CB3_P6_M3_CheckedChange(Checked As Boolean)
	textemp6 = ""
	If CB3_P6_M3.Checked Then
		textemp6 = CB3_P6_M3.Text
	Else
		textemp6 = ""
	End If
	If CB1_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB1_P6_M3.Text
	If CB2_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB2_P6_M3.Text
	If CB4_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB4_P6_M3.Text
	If CB5_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB5_P6_M3.Text
	If CB6_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB6_P6_M3.Text
	If CB7_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB7_P6_M3.Text
	Log(textemp6)
End Sub

Private Sub CB4_P6_M3_CheckedChange(Checked As Boolean)
	textemp6 = ""
	If CB4_P6_M3.Checked Then
		textemp6 = CB4_P6_M3.Text
	Else
		textemp6 = ""
	End If
	If CB1_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB1_P6_M3.Text
	If CB2_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB2_P6_M3.Text
	If CB3_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB3_P6_M3.Text
	If CB5_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB5_P6_M3.Text
	If CB6_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB6_P6_M3.Text
	If CB7_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB7_P6_M3.Text
	Log(textemp6)
End Sub

Private Sub CB5_P6_M3_CheckedChange(Checked As Boolean)
	textemp6 = ""
	If CB5_P6_M3.Checked Then
		textemp6 = CB5_P6_M3.Text
	Else
		textemp6 = ""
	End If
	If CB1_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB1_P6_M3.Text
	If CB2_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB2_P6_M3.Text
	If CB3_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB3_P6_M3.Text
	If CB4_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB4_P6_M3.Text
	If CB6_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB6_P6_M3.Text
	If CB7_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB7_P6_M3.Text
	Log(textemp6)
End Sub

Private Sub CB6_P6_M3_CheckedChange(Checked As Boolean)
	textemp6 = ""
	If CB6_P6_M3.Checked Then
		textemp6 = CB6_P6_M3.Text
	Else
		textemp6 = ""
	End If
	If CB1_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB1_P6_M3.Text
	If CB2_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB2_P6_M3.Text
	If CB3_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB3_P6_M3.Text
	If CB4_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB4_P6_M3.Text
	If CB5_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB5_P6_M3.Text
	If CB7_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB7_P6_M3.Text
	Log(textemp6)
End Sub

Private Sub CB7_P6_M3_CheckedChange(Checked As Boolean)
	textemp6 = ""
	If CB7_P6_M3.Checked Then
		textemp6 = CB7_P6_M3.Text
	Else
		textemp6 = ""
	End If
	If CB1_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB1_P6_M3.Text
	If CB2_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB2_P6_M3.Text
	If CB3_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB3_P6_M3.Text
	If CB4_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB4_P6_M3.Text
	If CB5_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB5_P6_M3.Text
	If CB6_P6_M3.Checked Then textemp6 = textemp6 & ", " & CB6_P6_M3.Text
	Log(textemp6)
End Sub

Private Sub CB1_P7_M3_CheckedChange(Checked As Boolean)
	textemp7 = ""
	If CB1_P7_M3.Checked Then
		textemp7 = CB1_P7_M3.Text
	Else
		textemp7 = ""
	End If
	If CB2_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB2_P7_M3.Text
	If CB3_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB3_P7_M3.Text
	If CB4_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB4_P7_M3.Text
	Log(textemp7)
End Sub

Private Sub CB2_P7_M3_CheckedChange(Checked As Boolean)
	textemp7 = ""
	If CB2_P7_M3.Checked Then
		textemp7 = CB2_P7_M3.Text
	Else
		textemp7 = ""
	End If
	If CB1_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB1_P7_M3.Text
	If CB3_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB3_P7_M3.Text
	If CB4_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB4_P7_M3.Text
	Log(textemp7)
End Sub

Private Sub CB3_P7_M3_CheckedChange(Checked As Boolean)
	textemp7 = ""
	If CB3_P7_M3.Checked Then
		textemp7 = CB3_P7_M3.Text
	Else
		textemp7 = ""
	End If
	If CB1_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB1_P7_M3.Text
	If CB2_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB2_P7_M3.Text
	If CB4_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB4_P7_M3.Text
	Log(textemp7)
End Sub

Private Sub CB4_P7_M3_CheckedChange(Checked As Boolean)
	textemp7 = ""
	If CB4_P7_M3.Checked Then
		textemp7 = CB4_P7_M3.Text
	Else
		textemp7 = ""
	End If
	If CB1_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB1_P7_M3.Text
	If CB2_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB2_P7_M3.Text
	If CB3_P7_M3.Checked Then textemp7 = textemp7 & ", " & CB3_P7_M3.Text
	Log(textemp7)
End Sub






Private Sub CB1_P8_M3_CheckedChange(Checked As Boolean)
	textemp8 = ""
	textemp8 = CB1_P8_M3.Text
	If CB2_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB2_P8_M3.Text
	If CB3_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB3_P8_M3.Text
	If CB4_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB4_P8_M3.Text
	Log(textemp8)
End Sub

Private Sub CB2_P8_M3_CheckedChange(Checked As Boolean)
	textemp8 = ""
	textemp8 = CB2_P8_M3.Text
	If CB1_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB1_P8_M3.Text
	If CB3_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB3_P8_M3.Text
	If CB4_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB4_P8_M3.Text
	Log(textemp8)
End Sub

Private Sub CB3_P8_M3_CheckedChange(Checked As Boolean)
	textemp8 = ""
	textemp8 = CB3_P8_M3.Text
	If CB1_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB1_P8_M3.Text
	If CB2_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB2_P8_M3.Text
	If CB4_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB4_P8_M3.Text
	Log(textemp8)
End Sub

Private Sub CB4_P8_M3_CheckedChange(Checked As Boolean)
	textemp8 = ""
	textemp8 = CB4_P8_M3.Text
	If CB1_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB1_P8_M3.Text
	If CB2_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB2_P8_M3.Text
	If CB3_P8_M3.Checked Then textemp8 = textemp8 & ", " & CB3_P8_M3.Text
	Log(textemp8)
End Sub

'Esta subrutina muestra las encuestas.
Sub Cuestionario
	Log("Entramos a Cuestionario")
	Private logger As Boolean = True
	b_encuesta_continuar.Visible = False
	et_encuesta.Visible = False
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	Private fecha As String = $"${DateTime.Date(DateTime.Now)} ${DateTime.Time(DateTime.Now)}"$
	CUANTOS = 0
'	indicePregunta = 0
	If logger Then Log($"Tomar_Foto = ${TOMAR_FOTO}"$)
	If TOMAR_FOTO = 0 Then
		s = B4XPages.MainPage.skmt.ExecQuery("select COUNT(*) AS CUANTOS from HIST_ENCUESTA where HE_CLIE In (Select cuenta from cuentaa)")
		s.Position= 0
		CUANTOS = s.GetString("CUANTOS")
		Private CUANTOS2 As Int = 0
		s = B4XPages.MainPage.skmt.ExecQuery("select COUNT(*) AS CUANTOS2 from HIST_ENCUESTA2 where HE_CLIENTE In (Select cuenta from cuentaa)")
		s.Position = 0
		CUANTOS2 = s.GetString("CUANTOS2")
		If logger Then LogColor($"Hist:encuesta=${CUANTOS}, hist_encuesta2 = ${CUANTOS2}"$, Colors.Magenta)
	End If
'	CUANTOS = 0
'	CUANTOS2 = 0
	If logger Then Log(CUANTOS & "|" & CUANTOS2)
	If CUANTOS = 0 And CUANTOS2 = 0 Then
		Private enc As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT CAT_EP_ID, CAT_EP_IDTIPOPREGUNTA, CAT_CE_DESCRIPCION, CAT_EP_PREGUNTA, CAT_EP_RES1_PRED, CAT_EP_RES2_PRED, CAT_EP_RES3_PRED, CAT_EP_ORDEN_PREGUNTA FROM CAT_ENCUESTA_PREGUNTA ORDER BY CAT_CE_DESCRIPCION, CAST(CAT_EP_ORDEN_PREGUNTA AS DECIMAL)")
		If enc.RowCount > 0 Then
			enc.position = 0
			If logger Then Log($"CAT_EP_ID=${enc.GetString("CAT_EP_ID")}"$)
			Private listaPreguntas As List
			listaPreguntas.Initialize
			For j = 0 To enc.RowCount - 1 'Ponemos en una lista los ID de las preguntas.
				enc.Position = j
				listaPreguntas.Add(enc.GetString("CAT_EP_ID"))
			Next
			If logger Then Log(listaPreguntas)
			enc.position = 0
			For i = 0 To enc.RowCount - 1
				Log("########################################################")
'				If logger Then Log($"ROWCOUNT: ${enc.RowCount}"$)
'				If logger Then Log($"tipo: ${enc.GetString("CAT_EP_IDTIPOPREGUNTA")}"$)
				If logger Then Log($"Tipo: ${enc.GetString("CAT_EP_IDTIPOPREGUNTA")}, CAT_EP_ID=${enc.GetString("CAT_EP_ID")}, CAT_EP_PREGUNTA=${enc.GetString("CAT_EP_PREGUNTA")}"$)
				If enc.GetString("CAT_EP_IDTIPOPREGUNTA") <> 4 And indicePregunta <> 0 Then
					indicePregunta = listaPreguntas.IndexOf(enc.GetString("CAT_EP_ID")) + 1 'Nos movemos a la posicion especificada por la respuesta, en las preguntas de tipo desicion, la respuesta nos indica a que pregunta movernos.
					i = indicePregunta
					Log($"i = ${i}"$)
				End If
				If logger Then Log("indicePregunta: " & indicePregunta & ", TIPO: " & enc.GetString("CAT_EP_IDTIPOPREGUNTA"))
'				Log($"Tomar_Foto = ${TOMAR_FOTO}"$)
				If logger Then Log($"EncuestaRes = ${encuestaRes}"$)
				If logger Then Log(listaPreguntas)
				If TOMAR_FOTO = 1 Then
					If CURSOR_FOTO + 1 > enc.RowCount -1 Then
						TOMAR_FOTO = 0
						LogColor("TOMAR FOTO = 1", Colors.Red)
						Exit
					Else
						i = CURSOR_FOTO + 1
					End If
					If logger Then Log($"i = ${i}"$)
					TOMAR_FOTO = 0
				End If
				If i > (enc.RowCount - 1) Then
					LogColor("MAS DE ${enc.RowCount - 1}", Colors.Red)
					Exit ' Si se contestó la ultima pregunta, entonces salimos.
				End If
				
'				indicePregunta = listaPreguntas.IndexOf(enc.GetString("CAT_EP_ID")) 'Nos movemos a la posicion especificada por la respuesta, en las preguntas de tipo desicion, la respuesta nos indica a que pregunta movernos.
				i = indicePregunta
				
				enc.Position = i
				Log($"POSICION = ${enc.Position}"$)
				If enc.GetString("CAT_EP_IDTIPOPREGUNTA") = 5 Then 'esto es para la foto
					If logger Then Log("Pregunta tipo 5")
					id_encuesta = enc.GetString("CAT_EP_ID")
					idencuestaaguardar = enc.GetString("CAT_EP_ID")
					LogColor(idencuestaaguardar,Colors.Blue)
					TOMAR_FOTO = 1
					CURSOR_FOTO = i
					LogColor("PREGUNTA TIPO 5 SALIMOS", Colors.Red)
					
					InitializeCamera2
					p_camara.Visible = True

					
				ELSE IF enc.GetString("CAT_EP_IDTIPOPREGUNTA") = 3 Then ' Tipo SI/NO
					If logger Then Log("Pregunta tipo 3")
					botonPresionado = 0 ' Bandera para que espere a que se conteste la pregunta
					l_titEncuesta.Text = enc.GetString("CAT_CE_DESCRIPCION")
					l_txtEncuesta.Text = enc.GetString("CAT_EP_PREGUNTA")
					Subs.centraEtiqueta(l_txtEncuesta, Root.Width)
					muestraBoton(b_encuesta_1,"SI", enc.GetString("CAT_EP_ID"), centroPantalla-350, 580, 300, 160)
					muestraBoton(b_encuesta_2, "NO", enc.GetString("CAT_EP_ID"), centroPantalla+50, 580, 300, 160)
					muestraEncuesta
					Log("Esperamos respuesta")
					Do Until botonPresionado = 1 'Esperamos que respondan la pregunta
						Sleep(0)
					Loop
					If logger Then Log("encuestaRes: " & encuestaRes)
					If logger Then LogColor($"Guardamos tipo 3 : ${encuestaRes}"$, Colors.Green)
					B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO, HE_LAT, HE_LON) VALUES (?,?,?,?,?,?)", Array As Object(la_cuenta.Text, encuestaRes, fecha, enc.GetString("CAT_EP_ID"), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
					ocultaPanelEncuesta
				ELSE IF enc.GetString("CAT_EP_IDTIPOPREGUNTA") = 4 Then
					If logger Then Log("Pregunta tipo 4")
					botonPresionado = 0 ' Bandera para que espere a que se conteste la pregunta
					l_titEncuesta.Text = enc.GetString("CAT_CE_DESCRIPCION")
					l_txtEncuesta.Text = enc.GetString("CAT_EP_PREGUNTA")
					If logger Then Log(enc.GetString("CAT_EP_PREGUNTA"))
					Subs.centraEtiqueta(l_txtEncuesta, Root.Width)
					muestraBoton(b_encuesta_1,"SI", enc.GetString("CAT_EP_ID"), centroPantalla-350, 580, 300, 160)
					muestraBoton(b_encuesta_2, "NO", enc.GetString("CAT_EP_ID"), centroPantalla+50, 580, 300, 160)
					muestraEncuesta
					Log("Esperamos respuesta")
					Do Until botonPresionado = 1 'Esperamos que respondan la pregunta
						Sleep(0)
					Loop
					If logger Then Log("encuestaRes: " & encuestaRes)
					If logger Then LogColor($"Guardamos tipo 4 : ${encuestaRes}"$, Colors.Green)
					If encuestaRes = "SI" Then
						B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO, HE_LAT, HE_LON) VALUES (?,?,?,?,?,?)", Array As Object(la_cuenta.Text, "SI", fecha, enc.GetString("CAT_EP_ID"), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
						indicePregunta = listaPreguntas.IndexOf(enc.GetString("CAT_EP_RES1_PRED")) 'Nos movemos a la posicion especificada por la respuesta, en las preguntas de tipo desicion, la respuesta nos indica a que pregunta movernos.
						Log($"IndicePreg = ${indicePregunta}"$)
						i = indicePregunta
					else if encuestaRes = "NO" Then
						B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO, HE_LAT, HE_LON) VALUES (?,?,?,?,?,?)", Array As Object(la_cuenta.Text, "NO", fecha, enc.GetString("CAT_EP_ID"), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
						indicePregunta = listaPreguntas.IndexOf(enc.GetString("CAT_EP_RES2_PRED")) 'Nos movemos a la posicion especificada por la respuesta, en las preguntas de tipo desicion, la respuesta nos indica a que pregunta movernos.
						Log($"IndicePreg = ${indicePregunta}"$)
						i = indicePregunta
						Log($"I = ${i}"$)
						If enc.GetString("CAT_EP_RES2_PRED") = "null" Or enc.GetString("CAT_EP_RES2_PRED") = Null Then
							Exit
						End If
					End If
				ELSE If enc.GetString("CAT_EP_IDTIPOPREGUNTA") = 2 Then ' Tipo 3 opciones.
					Log("Pregunta tipo 2")
					botonPresionado = 0 ' Bandera para que espere a que se conteste la pregunta.
					l_titEncuesta.Text = enc.GetString("CAT_CE_DESCRIPCION")
					l_txtEncuesta.Text = enc.GetString("CAT_EP_PREGUNTA")
					If logger Then Log(enc.GetString("CAT_EP_PREGUNTA"))
					muestraBoton(b_encuesta_1, enc.GetString("CAT_EP_RES1_PRED"), enc.GetString("CAT_EP_ID"), centroPantalla-250, 580, 500, 160)
					muestraBoton(b_encuesta_2, enc.GetString("CAT_EP_RES2_PRED"), enc.GetString("CAT_EP_ID"), centroPantalla-250, 740, 500, 160)
					muestraBoton(b_encuesta_3, enc.GetString("CAT_EP_RES3_PRED"), enc.GetString("CAT_EP_ID"), centroPantalla-250, 900, 500, 160)
					muestraEncuesta
					Log("Esperamos respuesta")
					Do Until botonPresionado = 1 'Esperamos que respondan la pregunta.
						Sleep(0)
					Loop
					Log("encuestaRes: " & encuestaRes)
					If logger Then LogColor($"Guardamos tipo 2 : ${encuestaRes}"$, Colors.Green)
					B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO, HE_LAT, HE_LON) VALUES (?,?,?,?,?,?)", Array As Object(la_cuenta.Text, encuestaRes, fecha, enc.GetString("CAT_EP_ID"), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
					
					indicePregunta = listaPreguntas.IndexOf(enc.GetString("CAT_EP_ID")) 'Nos movemos a la posicion especificada por la respuesta, en las preguntas de tipo desicion, la respuesta nos indica a que pregunta movernos.
					i =  indicePregunta + 1
					If i = enc.RowCount - 1 Then i = i - 1
					Log($"i = ${i}"$)
					ocultaPanelEncuesta
				ELSE If enc.GetString("CAT_EP_IDTIPOPREGUNTA") = 6 Then
					If logger Then Log("Pregunta tipo 6")
					Panel10.Visible = True
					l_chk_e.Text =  enc.GetString("CAT_EP_PREGUNTA")
					Chk_1.Checked = False
					chk_2.Checked = False
					chk_3.Checked = False
					Chk_1.Text = enc.GetString("CAT_EP_RES1_PRED")
					chk_2.Text =  enc.GetString("CAT_EP_RES2_PRED")
					chk_3.Text =  enc.GetString("CAT_EP_RES3_PRED")
					chk_1_valor =  enc.GetString("CAT_EP_RES1_PRED")
					chk_2_valor =  enc.GetString("CAT_EP_RES2_PRED")
					chk_3_valor =  enc.GetString("CAT_EP_RES3_PRED")
					Chk_1.Tag = enc.GetString("CAT_EP_ID")
					chk_2.Tag = enc.GetString("CAT_EP_ID")
					chk_3.Tag = enc.GetString("CAT_EP_ID")
					TOMAR_FOTO = 1
					CURSOR_FOTO = i
					Exit
				ELSE If enc.GetString("CAT_EP_IDTIPOPREGUNTA") = 1 Then
					Log("Pregunta tipo 1")
					botonPresionado = 0 ' Bandera para que espere a que se conteste la pregunta
					l_titEncuesta.Text = enc.GetString("CAT_CE_DESCRIPCION")
					l_txtEncuesta.Text = enc.GetString("CAT_EP_PREGUNTA")
					If logger Then Log(enc.GetString("CAT_EP_PREGUNTA") &"|"&enc.GetString("CAT_EP_ORDEN_PREGUNTA"))
					Subs.centraEditText(et_encuesta, Root.Width)
					et_encuesta.Visible = True
					b_encuesta_continuar.Enabled = False
					Private bTop = et_encuesta.Top + 130
					muestraBoton(b_encuesta_continuar,"Continuar", enc.GetString("CAT_EP_ID"), centroPantalla-250, bTop, 500, 160)
					muestraEncuesta
					Log("Esperamos respuesta")
					Do Until botonPresionado = 1 'Esperamos que respondan la pregunta
						Sleep(0)
					Loop
					Log($"Respuesta: ${encuestaRes}"$)
					If logger Then LogColor($"Guardamos tipo 1 : ${encuestaRes}"$, Colors.Green)
					B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_RES, HE_FECHA, HE_TIPO, HE_LAT, HE_LON) VALUES (?,?,?,?,?,?)", Array As Object(la_cuenta.Text, encuestaRes, fecha, enc.GetString("CAT_EP_ID"), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps))
					ocultaPanelEncuesta
				Else
'					Starter.tipov = "VENTA"
					B4XPages.ShowPage("productos")
				End If
				If i = enc.RowCount - 1 Then
					i = i - 1
				End If
			Next
			enc.Close
		Else
'			Starter.tipov = "VENTA"
			B4XPages.ShowPage("productos")
		End If
	Else
'		Starter.tipov = "VENTA"
		B4XPages.ShowPage("productos")
	End If
	
End Sub

'Muestra el panel de la encuesta, le da el alto y ancho de la pantalla y la pone en 0,0
Sub muestraEncuesta
	Log("Muestra Encuesta")
	p_encuesta.Top = 0
	p_encuesta.left = 0
	p_encuesta.Height = GetDeviceLayoutValues.Height
	p_encuesta.Width = GetDeviceLayoutValues.Width
	p_encuesta.SetVisibleAnimated(200, True)
	p_encuesta.Elevation = 90 'ignore
	p_encuesta.BringToFront
'	P_INF_GENERAL.Visible = False
'	Log("Panel general="&P_INF_GENERAL.Visible)
End Sub

' Oculta el panel de la encuesta y los botones de la misma.
Sub ocultaPanelEncuesta
'	Log("Oculta Encuesta")
	b_encuesta_1.Visible = False
	b_encuesta_2.Visible = False
	b_encuesta_3.Visible = False
	p_encuesta.Visible = False
'	P_INF_GENERAL.Visible = True
'	If logger Then Log("Panel general="&P_INF_GENERAL.Visible)
End Sub

'Regresa el valor de "left" para el centro de la pantalla
Sub centroPantalla As Int
	Private anchoPantalla As Int = GetDeviceLayoutValues.Width
	Private anchoPantalla As Int = Root.Width
	Return anchoPantalla/2
End Sub

Private Sub b_encuesta_1_Click
	Log("BOTON 1 CLICK")
	Dim btn As Button = Sender
	Log("BOTON 1 CLICKED "& " clicked - " & btn.Text & " - " & btn.Tag)
	encuestaRes = btn.Text
	indicePregunta = btn.Tag
	ocultaPanelEncuesta
	botonPresionado = 1
End Sub

Private Sub b_encuesta_2_Click
	Log("BOTON 2 CLICK")
	Dim btn As Button = Sender
	Log("BOTON 2 CLICKED "& " clicked - " & btn.Text & " - " & btn.Tag)
	encuestaRes = btn.Text
	indicePregunta = btn.Tag
	ocultaPanelEncuesta
	botonPresionado = 1
End Sub

Private Sub b_encuesta_3_Click
	Log("BOTON 3 CLICK")
	Dim btn As Button = Sender
	Log("BOTON 3 CLICKED "& " clicked - " & btn.Text & " - " & btn.Tag)
	encuestaRes = btn.Text
	indicePregunta = btn.Tag
	ocultaPanelEncuesta
	botonPresionado = 1
End Sub

Private Sub b_encuesta_continuar_Click
	Dim btn As Button = Sender
	Log("BOTON CONTINUAR CLICK - " & btn.Text & " - " & btn.Tag)
	encuestaRes = et_encuesta.Text
	indicePregunta = btn.Tag
	et_encuesta.Text = ""
	et_encuesta.Visible = False
	b_encuesta_continuar.Visible = False
	ocultaPanelEncuesta
	botonPresionado = 1
End Sub

Private Sub et_encuesta_TextChanged (Old As String, New As String)
'	Log($"|${Old}|,|${New}|"$)
	If New.Length > 0 Then b_encuesta_continuar.Enabled = True
	If New.Length < 1 Then b_encuesta_continuar.Enabled = False
End Sub

'Muestra un boton con las dimensiones, posicion y texto especificados.
Sub muestraBoton (thisButton As Button, theText As String, theTag As String, Left As Int, Top As Int, width As Int, height As Int)
	thisButton.Text = theText
	thisButton.Tag = theTag
	thisButton.Left = Left
	thisButton.Top = Top
	thisButton.Width = width
	thisButton.Height = height
	thisButton.Visible = True
End Sub

'Muestra un boton con las dimensiones, posicion y texto especificados.
Sub muestraBotonCentrado (thisButton As Button, theText As String, theTag As String, Top As Int, width As Int, height As Int) 'ignore
	Private anchoPantalla As Int
	thisButton.Text = theText
	thisButton.Tag = theTag
	anchoPantalla = GetDeviceLayoutValues.Width
	thisButton.Left = (anchoPantalla/2) - (width/2)
	thisButton.Top = Top
	thisButton.Width = width
	thisButton.Height = height
	thisButton.Visible = True
End Sub

Private Sub l_chk_e_Click
	
End Sub

Private Sub b_chk_e_Click
	
End Sub

Private Sub Panel10_Click
	
End Sub

Private Sub p_encuesta_Click
	
End Sub

Sub cuest_preguntaContestada(m As Map)
'	Recibimos el id de la pregunta, el id de la respuesta, el texto de la respuesta y el objeto del panelSombra para poder ocultarlo.
	Log(m)
'	If q.IsInitialized Then Log($"${q.encuestaIniciada}|${q.preguntaActual}"$)
'	m.Get("panel").As(Panel).Visible = False 'Ocultamos el panel de la pregunta.
	m.Get("panel").As(Panel).RemoveView 'Quitamos le panel de la pregunta
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	B4XPages.MainPage.skmt.ExecNonQuery($"delete from CUESTIONARIO where Q_IDCLIENTE = '${Subs.traeCliente}' and Q_IDPREGUNTA = '${m.Get("idPregunta")}'"$)
	B4XPages.MainPage.skmt.ExecNonQuery($"insert into CUESTIONARIO (Q_RUTA, Q_ALMACEN, Q_IDCLIENTE, Q_IDPREGUNTA, Q_PREGUNTA, Q_IDRESPUESTA, Q_RESPUESTA, Q_FECHA) values ('${Subs.traeRuta}', '${Subs.traeAlmacen}', '${Subs.traeCliente}', '${m.Get("idPregunta")}', '${m.Get("pregunta")}', '${m.Get("idRespuesta")}', '${m.Get("respuesta")}', '${DateTime.Date(DateTime.now)} ${DateTime.time(DateTime.now)}')"$)
	Log(">> RESP: " & m.Get("respuesta"))
	Select Case m.Get("idPregunta")
		Case "1"
			If m.Get("respuesta") = "Ninguno de los anteriores" Then
'				Log("Ninguno de los anteriores")
'				ToastMessageShow("Ninguno de los anteriores", False)
				cuest.agregaPreguntaCheckbox("3", "¿Qué productos de Kileo Gato encuentras en esta tienda?", Array As String("Whiskas","KITEKAT","PAL GATO","CAT CHOW","GATINA","MININO","MI MISHI","OTROS","Ninguno de los anteriores"))
			Else
'				Log(m.Get("idRespuesta"))
				cuest.agregaPreguntaAbierta("2", "Captura el precio por kilo de los articulos seleccionados anteriormente", cuest.strToList(m.Get("idRespuesta")), cuest.strToList(m.Get("respuesta")))
			End If
		Case "2"
'			Log(m.Get("respuesta"))
			cuest.agregaPreguntaCheckbox("3", "¿Qué productos de Kileo Gato encuentras en esta tienda?", Array As String("Whiskas","KITEKAT","PAL GATO","CAT CHOW","GATINA","MININO","MI MISHI","OTROS","Ninguno de los anteriores"))
		Case "3"
'			Log(m.Get("respuesta"))
			If m.Get("respuesta") = "Ninguno de los anteriores" Then
'				Log("Ninguno de los anteriores")
'				ToastMessageShow("Ninguno de los anteriores", False)
				cuest.agregaPreguntaCheckbox("5", "¿Qué productos de húmedo MARS encuentras en esta tienda?", Array As String("Pedigree Adulto res","Pedigree Adulto Pollo","Pedigree Cachorro res","Pedigree Cachorro Pollo","Pedigree Raz Peq res","Pedigree Raz Peq Pollo","Pedigree Adulto Cordero","Pedigree Adulto Lata res","Whiskas Atún","Whiskas Pollo","Whiskas res","Whiskas Salmón","Whiskas Parrillada Mixta","Whiskas Pescado BLANCO","Whiskas Souffle","Ninguno de los anteriores"))
			Else
				cuest.agregaPreguntaAbierta("4", "Captura el precio por kilo de los articulos seleccionados anteriormente", cuest.strToList(m.Get("idRespuesta")), cuest.strToList(m.Get("respuesta")))
			End If
		Case "4"
			cuest.agregaPreguntaCheckbox("5", "¿Qué productos de húmedo MARS encuentras en esta tienda?", Array As String("Pedigree Adulto res","Pedigree Adulto Pollo","Pedigree Cachorro res","Pedigree Cachorro Pollo","Pedigree Raz Peq res","Pedigree Raz Peq Pollo","Pedigree Adulto Cordero","Pedigree Adulto Lata res","Whiskas Atún","Whiskas Pollo","Whiskas res","Whiskas Salmón","Whiskas Parrillada Mixta","Whiskas Pescado BLANCO","Whiskas Souffle","Ninguno de los anteriores"))
		Case "5"
			cuest.agregaPreguntaCheckbox("6", "¿Qué productos de húmedo otros encuentras en esta tienda?", Array As String("Dog Chow (cualquier sabor)","Ganador (cualquier sabor)","Felix (cualquier sabor)","Minino plus (cualquier sabor)","Cat Chow (cualquier sabor)","Beneful (cualquier sabor)","Amigo Gourmet (cualquier sabor)","Ninguno de los anteriores"))
		Case "6"
			cuest.agregaPreguntaCheckbox("7", "¿Qué productos de botanas encuentras en esta tienda?", Array As String("Dentastix","Biscrok","Ninguno de los anteriores"))
		Case "7"
'			Log(m.Get("respuesta"))
			ToastMessageShow(m.Get("respuesta"), False)
			Log(">>>>>>>>>>  " & cuest.encuestaIniciada)
			cuest.encuestaIniciada = False
			Log(">>>>>>>>>>  " & cuest.encuestaIniciada)
'			refrescarCliente = True
'			Log($"####  REFRESCAR CLIENTE -> ${refrescarCliente}"$)
			B4XPage_Appear
'		Case 6
	End Select
End Sub


'tomar foto

'Private Sub InitializeCamera2
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
'	Wait For B4XPage_PermissionResult (Permission As String, resultC As Boolean)
'	If resultC Then
'		camEx.Initialize(p_cam, frontCamera, Me, "Camera1")
'		frontCamera = camEx.Front
'		Log("inicializamos Camara")
'	Else
'		ToastMessageShow("No permission!!!", True)
'	End If
''	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
''	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
''	If Result Then
''		Log("conpermisos para escritura")
''	Else
''		ToastMessageShow("No permission!!!", True)
''	End If
''	
''	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_EXTERNAL_STORAGE)
''	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
''	If Result Then
''		Log("conpermisos para escritura")
''	Else
''		ToastMessageShow("No permission!!!", True)
''	End If
'End Sub

'Sub Camera1_Ready (Success As Boolean)
'	Log("Camara ready")
'	If Success Then
'		camEx.SetJpegQuality(90)
'		camEx.SetContinuousAutoFocus
'		camEx.CommitParameters
'		camEx.StartPreview
'		Log(camEx.GetPreviewSize)
'	Else
'		ToastMessageShow("Cannot open camera.", True)
'		Log("Cannot open camera")
'	End If
'End Sub
'
'Sub Camera1_PictureTaken (Data()As Byte)
'	Log("tome foto")
'	Dim filename As String = DateTime.Now & "GUNA.jpg"
'	Dim Dirp As String = File.DirInternal
'	Dim Dir As String
'	Dim Dir2 As String
'	Try
'		File.MakeDir(Dirp,"/guna")
'		Dir = "/guna"
'		Log("creado en promotoria " & Dirp & Dir)
'	Catch
'		Dir = ""
'		Log("creado en raiz")
'	End Try
'	
'	Try
'		File.MakeDir(Dirp & Dir,"/reduccion")
'		Dir2 = "/reduccion"
'		Log("creado en promotoria " & Dirp & Dir & Dir2)
'	Catch
'		Dir = ""
'		Log("creado en raiz")
'	End Try
'	
'	camEx.SavePictureToFile(Data, Dirp&Dir, filename)
'	Log(Dirp&Dir &"  ALGO BONITO COMO UN COLOR PARA GUERRA  "& filename)
'	camEx.StartPreview 'restart preview
''	ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename, True)
'	Log("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename)
'	p_camara.Visible = False
'	
'	Log(filename)
'	
'	
'	If filename <> "0" Then
'		Dim img As B4XBitmap = xui.LoadBitmapResize(File.DirInternal & Dir, filename, 300, 450, True)
'		Dim out As OutputStream = File.OpenOutput(File.DirInternal & Dir & Dir2, filename, True)
'		img.WriteToStream(out, 100, "PNG")
'		out.Close
'		Private fecha As String = $"${DateTime.Date(DateTime.Now)} ${DateTime.Time(DateTime.Now)}"$
'		B4XPages.MainPage.skmt.ExecNonQuery2("insert into HIST_ENCUESTA(HE_CLIE, HE_FOTO, HE_FECHA, HE_TIPO, HE_LAT, HE_LON,HE_RES) VALUES (?,?,?,?,?,?,?)", Array As Object(la_cuenta.Text, File.ReadBytes(File.DirInternal &  Dir & Dir2, filename), fecha, idencuestaaguardar, B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps,"FOTO"))
'	End If
'	StopCamera2
''	nombrefoto = "0"
'	ocultaPanelEncuesta
'End Sub
'
'Private Sub p_camara_Click
'	
'End Sub
'
'Private Sub b_foto_Click
'	camEx.TakePicture
'	p_camara.Visible = False
''	StopCamera2
'End Sub
'
'Private Sub StopCamera2
''	Capturing = False
'	If camEx.IsInitialized Then
'		camEx.Release
'	End If
'End Sub

Private Sub b_Inicio_Fin_venta_Click
''	b_Inicio_Fin_venta.Visible = False
''	Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, Subs.traeAlmacen, Subs.traeRuta, "Pre-venta", "0", Subs.fechanormal(DateTime.Now), Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, "", "")
'	contadorIniciarVenta = 0
'	IniVenNO = False
'	If dentroDeGeocerca Then precision = 1
''	LogColor("-------> "&contadorIniciarVenta & " <-------", Colors.Red)
'	motivoNoVenta = ""
'	motivoNoVisita = ""
'	p_transparenteInicioFin.Visible = False
'	If b_Inicio_Fin_venta.Text = "TERMINAR VENTA" Then
'		Subs.bitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRutaBitacora, "Termina Venta", Subs.traeCliente, "", Subs.fechanormal(DateTime.Now), B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, motivoNoVenta, motivoNoVisita,b_geo)
'		bitacora.enVenta = False
''		LogColor($">>>>>> TERMINA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
'		B4XPages.ShowPageAndRemovePreviousPages("Principal")
''		guardadoventa
'	Else if b_Inicio_Fin_venta.Text = "INICIAR VENTA" Then
'		contadorIniciarVenta = 0
'		IniVenNO = False
'		contadorIniciarVenta = contadorIniciarVenta + 1
'		If contadorIniciarVenta = 1 And IniVenNO = False And motivoNoVenta <> "NO VENTA" Then
'			IniVenNO = True
'			Subs.bitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRutaBitacora, "Inicia Venta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), "", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, "", "",b_geo)
'			bitacora.enVenta = True
''			LogColor($">>>>>> INICIA VENTA: ${Starter.enVenta} - ${Subs.traeCliente}"$, Colors.red)
'		Else If contadorIniciarVenta = 1 And IniVenNO = False And motivoNoVenta = "NO VENTA" Then
'			IniVenNO = True
'			Subs.bitacora(Subs.fechanormal(DateTime.Now), Subs.traeUsuarioDeBD, Subs.traeAlmacen, Subs.traeRutaBitacora, "Inicia Venta", Subs.traeCliente, Subs.fechanormal(DateTime.Now), "", B4XPages.MainPage.lat_gps, B4XPages.MainPage.lon_gps, precision, motivoNoVenta, "",b_geo)
'			bitacora.enVenta = True
'		Else If contadorIniciarVenta > 1 Then
'			b_Inicio_Fin_venta.Visible = False
'		End If
'	End If
'
'	b_Inicio_Fin_venta.Visible = False
End Sub

Private Sub LA_GEO_Click
	Log(geoCont)
	If geoCont = 3 Then
		Subs.centraPanel(p_pideGeoPass, Root.Width)
		geoCont = 0
		If distance > 99 Then
			p_pideGeoPass.BringToFront
			et_geopass.RequestFocus
			p_pideGeoPass.Visible = True
		End If
	End If
	geoCont = geoCont + 1
End Sub

Private Sub p_transparenteInicioFin_Click
	
End Sub

Private Sub b_preventa_Click
	
End Sub

Private Sub p_transparenteTicketImpreso_Click

End Sub

Private Sub b_codigoAutorizacion_Click
	If et_codigoAutorizacion.Text <> "KMTS1" Then
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_codigoAutorizacion"
		cmd.Parameters = Array As Object(et_codigoAutorizacion.Text.Trim, Subs.traeRuta, Subs.traeAlmacen)
		reqManager.ExecuteQuery(cmd , 0, "codigoAutorizacion")
	Else
		Starter.skmt.ExecNonQuery("delete from ticket_impreso where idCliente in (select cuenta from cuentaa)")
		p_transparenteTicketImpreso.Visible = False
		et_codigoAutorizacion.Text = ""
		Starter.skmt.ExecNonQuery("Update kmt_info3 set CONFIRMADO = 0  WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)")
		Starter.skmt.ExecNonQuery("Update CODIGOS_CREDITO set BANDERA = 0  WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	End If
	teclado.HideKeyboard
'	p_transparenteTicketImpreso.Visible = False
End Sub

Private Sub b_cancelarCodigoAutorizacion_Click
	p_transparenteTicketImpreso.Visible = False
End Sub

Private Sub PDFGENERAR
	ESPACIO = 0
'	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	Dim PDF As cPDF
	'initialize with mm unit
	PDF.Initialize("mm")
	'set properties
	PDF.sProperty(PDF.PropertyAuthor,"Keymonsoft"). _
	    sProperty(PDF.PropertyTitle,"Ticket"). _
		sProperty(PDF.PropertyKeywords,"B4X,PDF,Cross platform")
	'add a page
	
	
'	s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU,IFNULL(PE_RECALCULO,0) AS PE_RECALCULO, length(PE_COSTOU) as L_COSTOU, length(Ifnull(PE_RECALCULO,0)) as L_COSTOREC,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT,PE_CANT * IFNULL(PE_RECALCULO,0) AS  PE_COSTO_TOTREC, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,length(PE_CANT * IFNULL(PE_RECALCULO,0)) as L_COSTO_TOTREC,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_CEDIS = ? AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String(Subs.traeAlmacen))
	Dim s56 As Cursor=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU,IFNULL(PE_RECALCULO,0) AS PE_RECALCULO, length(PE_COSTOU) as L_COSTOU, length(Ifnull(PE_RECALCULO,0)) as L_COSTOREC,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT,PE_CANT * IFNULL(PE_RECALCULO,0) AS  PE_COSTO_TOTREC, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,length(PE_CANT * IFNULL(PE_RECALCULO,0)) as L_COSTO_TOTREC,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA"))
	Dim s57 As Cursor = skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU,IFNULL(PE_RECALCULO,0) AS PE_RECALCULO, length(PE_COSTOU) as L_COSTOU, length(Ifnull(PE_RECALCULO,0)) as L_COSTOREC,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT,PE_CANT * IFNULL(PE_RECALCULO,0) AS  PE_COSTO_TOTREC, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,length(PE_CANT * IFNULL(PE_RECALCULO,0)) as L_COSTO_TOTREC,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) > 3  AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by  PE_CEDIS, PE_COSTOU", Array As String("PREVENTA"))
	
	Dim pagina As Double = ((18 + (s56.RowCount*2) + (s57.RowCount*2)) * (6)) + 25
'	Dim pagina As Double = ((18 + s56.RowCount + s57.RowCount +2) * (6)) + 18
	Dim multiplicador As Int = 0
	PDF.pageAdd(-300,pagina)
'	pdf.pageAdd(-350,-1900)
	
	PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
	
	PDF.outImage(xui.DefaultFolder,"guna-fondo.jpg",1,pagina-45,45,0)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"GUNA")
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,sDate& " " & sTime)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Vendedor:" & Subs.traeUsuarioDeBD)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Tienda: " & La_nombre.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"ID.Cliente: " &  la_cuenta.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Calle: " & la_Calle.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Colonia: " & la_col.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," ")
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," ")
	c = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ?",Array As String("PREVENTA"))
	If c.RowCount > 0 Then
		
		
		If ALMACEN = 88 Then
			
			s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU,IFNULL(PE_RECALCULO,0) AS PE_RECALCULO, length(PE_COSTOU) as L_COSTOU, length(Ifnull(PE_RECALCULO,0)) as L_COSTOREC,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT,PE_CANT * IFNULL(PE_RECALCULO,0) AS  PE_COSTO_TOTREC, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,length(PE_CANT * IFNULL(PE_RECALCULO,0)) as L_COSTO_TOTREC,PE_PROID, PE_CEDIS, PE_RECCANT FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA"))
			If S.RowCount>0 Then
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"------------------------------------PREVENTA-----------------------------------------")
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"Cant.                                    Precio                                    Importe")
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------")
				For i=0 To S.RowCount -1
					S.Position=i
					
					If s.GetDouble("PE_RECALCULO") = 0 Then
						If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
						Else
							PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
'							LogColor(s.GetLong("L_CANT"),Colors.Magenta)
'							LogColor(s.GetLong("L_COSTOU"),Colors.Magenta)
'							LogColor(s.GetLong("L_COSTO_TOT"),Colors.Magenta)
							TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOU") + s.GetLong("L_COSTO_TOT")
							ESPACIO = 92
							BLANCO = " "
							ESPACIO = ESPACIO - TAMANO
							ESPACIO = ESPACIO / 2
							For E=0 To ESPACIO -1
								BLANCO = " " & BLANCO
							Next
							PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6, s.GETSTRING("PE_CANT") & BLANCO & s.GETSTRING("PE_COSTOU") & BLANCO & s.GETSTRING("PE_COSTO_TOT"))
'							PDF.outtext(1,108-9*6,s.GETSTRING("PE_COSTOU"))
'
'							PDF.outtext(1,108-9*6,s.GETSTRING("PE_COSTO_TOT")  )
						End If
					Else if s.GetDouble("PE_CANT") = s.GetDouble("PE_RECCANT") Then
						If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
						Else
							PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
'							LogColor(s.GetLong("L_CANT"),Colors.Magenta)
'							LogColor(s.GetLong("L_COSTOU"),Colors.Magenta)
'							LogColor(s.GetLong("L_COSTO_TOT"),Colors.Magenta)
							TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOREC") + s.GetLong("L_COSTO_TOTREC")
							ESPACIO = 92
							BLANCO = " "
							ESPACIO = ESPACIO - TAMANO
							ESPACIO = ESPACIO / 2
							For E=0 To ESPACIO -1
								BLANCO = " " & BLANCO
							Next
							PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6, s.GETSTRING("PE_CANT") & BLANCO & s.GETSTRING("PE_RECALCULO") & BLANCO & s.GETSTRING("PE_COSTO_TOTREC"))
'							PDF.outtext(1,108-9*6,s.GETSTRING("PE_COSTOU"))
'
'							PDF.outtext(1,108-9*6,s.GETSTRING("PE_COSTO_TOT")  )
						End If
					Else if s.GetDouble("PE_CANT") <> s.GetDouble("PE_RECCANT") Then
					
'						Con Descuento
						If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
						Else
							PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
							TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOREC") + s.GetLong("L_COSTO_TOTREC")
							ESPACIO = 92
							BLANCO = " "
							ESPACIO = ESPACIO - TAMANO
							ESPACIO = ESPACIO / 2
							For E=0 To ESPACIO -1
								BLANCO = " " & BLANCO
							Next
							PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6, s.GETSTRING("PE_RECCANT") & BLANCO & s.GETSTRING("PE_RECALCULO") & BLANCO & NumberFormat2((s.GETSTRING("PE_RECCANT")*s.GETSTRING("PE_RECALCULO")),1,2,2,False))
						End If
						
'						Sin descuento
						If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
						Else
							Private subTot As String = (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) * s.GETSTRING("PE_COSTOU")
							PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
							TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOU") + s.GetLong("L_COSTO_TOTREC")
							ESPACIO = 92
							BLANCO = " "
							ESPACIO = ESPACIO - TAMANO
							ESPACIO = ESPACIO / 2
							For E=0 To ESPACIO -1
								BLANCO = " " & BLANCO
							Next
							PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
							multiplicador = multiplicador +1
							PDF.outtext(1,pagina-multiplicador*6, (s.GETSTRING("PE_CANT")-s.GETSTRING("PE_RECCANT")) & BLANCO & s.GETSTRING("PE_COSTOU") & BLANCO & NumberFormat2(subTot,1,2,2,False))
						End If
						
					End If
					
				Next
				PDF.outtext(1,108-9*6," " )
			End If
			s.Close
		Else
		
			s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA"))
			If S.RowCount>0 Then
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"------------------------------------PREVENTA-----------------------------------------")
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"Cant.                                    Precio                                    Importe")
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------")
				For i=0 To S.RowCount -1
					S.Position=i
					If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
						multiplicador = multiplicador +1
						PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
					Else
						PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
						multiplicador = multiplicador +1
						PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
'					LogColor(s.GetLong("L_CANT"),Colors.Magenta)
'					LogColor(s.GetLong("L_COSTOU"),Colors.Magenta)
'					LogColor(s.GetLong("L_COSTO_TOT"),Colors.Magenta)
						TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOU") + s.GetLong("L_COSTO_TOT")
						ESPACIO = 92
						BLANCO = " "
						ESPACIO = ESPACIO - TAMANO
						ESPACIO = ESPACIO / 2
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
						multiplicador = multiplicador +1
						PDF.outtext(1,pagina-multiplicador*6, s.GETSTRING("PE_CANT") & BLANCO & s.GETSTRING("PE_COSTOU") & BLANCO & s.GETSTRING("PE_COSTO_TOT"))
'					pdf.outtext(1,108-9*6,s.GETSTRING("PE_COSTOU"))

'					pdf.outtext(1,108-9*6,s.GETSTRING("PE_COSTO_TOT")  )
					End If
				Next
				PDF.outtext(1,108-9*6," " )
			End If
			s.Close
			s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) > 3  AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by  PE_CEDIS, PE_COSTOU", Array As String("PREVENTA"))
			If S.RowCount>0 Then
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"--------------------------PROMOS PREVENTA-------------------------------------")
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"Cant.                                   Precio                                    Importe")
				multiplicador = multiplicador +1
				PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------")
				For i=0 To S.RowCount -1
					S.Position=i
					If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
						multiplicador = multiplicador +1
						PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
					Else
						PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
						multiplicador = multiplicador +1
						PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
						LogColor(s.GetLong("L_CANT"),Colors.Magenta)
						LogColor(s.GetLong("L_COSTOU"),Colors.Magenta)
						LogColor(s.GetLong("L_COSTO_TOT"),Colors.Magenta)
						TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOU") + s.GetLong("L_COSTO_TOT")
						ESPACIO = 92
						BLANCO = " "
						ESPACIO = ESPACIO - TAMANO
						ESPACIO = ESPACIO / 2
						For E=0 To ESPACIO -1
							BLANCO = " " & BLANCO
						Next
						PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
						multiplicador = multiplicador +1
						PDF.outtext(1,pagina-multiplicador*6, s.GETSTRING("PE_CANT") & BLANCO & s.GETSTRING("PE_COSTOU") & BLANCO & s.GETSTRING("PE_COSTO_TOT"))
					End If
				Next
			End If
		End If
		
		s.Close
'		multiplicador = multiplicador +1
'		pdf.outtext(1,pagina-multiplicador*6," " )
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6," " )
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------")
		
	
	
		
		
		
		
		
		s=skmt.ExecQuery("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
		s.Position =0
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6,"Subtotal preventa:   $" & s.GetString("TOTAL") )
'		s.Close
		c= skmt.ExecQuery2("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) AND PE_FOLIO = ?", Array As String("PREVENTA"))
		C.Position=0
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6,"Total articulos preventa:   " & c.GetString("PC_NOART") )
'		c.Close
		
		Dim s3 As Cursor =skmt.ExecQuery("select IFNULL(SUM(PE_COSTO_TOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) = 0")
		s3.Position =0
		S2=skmt.ExecQuery("select IFNULL(SUM(PE_RECALCULOTOT),0) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and IFNULL(PE_RECALCULO,0) <> 0")
		S2.Position =0
	
		If NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False) <> s.GetString("TOTAL") Then
			multiplicador = multiplicador +1
			Log(s.GetString("TOTAL") & "|" & Subs.calculaTotalConPromoXRango(Subs.traeCliente))
			PDF.outtext(1,pagina-multiplicador*6,"Descuento:   $" & NumberFormat2( s.GetString("TOTAL")-Subs.calculaTotalConPromoXRango(Subs.traeCliente),0,2,2,False) )
'			Printer1.WriteString("Descuento:   $" & NumberFormat2( s.GetString("TOTAL")-(s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False)&  CRLF)
		End If
		multiplicador = multiplicador +1
'		PDF.outtext(1,pagina-multiplicador*6,"Total Preventa:   $" & NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False) )
		PDF.outtext(1,pagina-multiplicador*6,"Total Preventa:   $" & NumberFormat2(Subs.calculaTotalConPromoXRango(Subs.traeCliente),0,2,2,False) )
'		Printer1.WriteString("Total Preventa:   $" & NumberFormat2((s3.GetString("TOTAL") + S2.GetString("TOTAL")),0,2,2,False)&  CRLF)
		
		
		
	End If
'	multiplicador = multiplicador +1
'	pdf.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"--------------------------ESTE TICKET NO ES UN ---------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"-------------------COMPROBANTE FISCAL, SOLO ES--------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"---------------------------------INFORMATIVO-----------------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
'	multiplicador = multiplicador +1
'	PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------" )
'	'all combinations of font normal, bold,italic,underline and strikethrough
'	For i=0 To 15
'		'select a font
'		pdf.sFont(pdf.fontHelvetica,s,30,pdf.colorBlack)
'		'draw a text at position 20 (from left) and 277 (from bottom)
'		pdf.outtext(20,277-i*15,"Hello world!")
'	Next
	DateTime.DateFormat = "ddmmyyyy"
	DateTime.TimeFormat = "HHmmss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	archivoTicketPDF = sDate&sTime&".pdf"
	'save to file with compression if data compressed are smaller
	savePDF(PDF, archivoTicketPDF, PDF.CompressAlways)
	'open with default viewer
'	openPDF(sDate&sTime&".pdf")
End Sub

Private Sub PDFGENERAR2
	ESPACIO = 0
	DateTime.DateFormat = "MM/dd/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	Dim PDF As cPDF
	'initialize with mm unit
	PDF.Initialize("mm")
	'set properties
	PDF.sProperty(PDF.PropertyAuthor,"Keymonsoft"). _
	    sProperty(PDF.PropertyTitle,"Ticket"). _
		sProperty(PDF.PropertyKeywords,"B4X,PDF,Cross platform")
	'add a page
	
	Dim s56 As Cursor=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA"))
	Dim s57 As Cursor = skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) > 3  AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by  PE_CEDIS, PE_COSTOU", Array As String("PREVENTA"))
	
	Dim pagina As Double = ((18 + (s56.RowCount*2) + (s57.RowCount*2)) * (6)) + 12
'	Dim pagina As Double = ((18 + s56.RowCount + s57.RowCount +2) * (6)) + 18
	Dim multiplicador As Int = 0
	PDF.pageAdd(-300,pagina)
'	pdf.pageAdd(-350,-1900)
	
	PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
	
	PDF.outImage(xui.DefaultFolder,"guna-fondo.jpg",1,pagina-45,45,0)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"GUNA")
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,sDate& " " & sTime)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Vendedor:" & Subs.traeUsuarioDeBD)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Tienda: " & La_nombre.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"ID.Cliente: " &  la_cuenta.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Calle: " & la_Calle.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"Colonia: " & la_col.Text)
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," ")
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," ")
	c = skmt.ExecQuery2("SELECT * FROM PEDIDO WHERE PE_FOLIO = ?",Array As String("PREVENTA"))
	If c.RowCount > 0 Then
		s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) < 4 AND PE_CLIENTE IN (Select CUENTA from cuentaa)  order by  PE_PROID", Array As String("PREVENTA"))
		If S.RowCount>0 Then
			multiplicador = multiplicador +1
			PDF.outtext(1,pagina-multiplicador*6,"------------------------------------PREVENTA-----------------------------------------")
			multiplicador = multiplicador +1
			PDF.outtext(1,pagina-multiplicador*6,"Cant.                                    Precio                                    Importe")
			multiplicador = multiplicador +1
			PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------")
			For i=0 To S.RowCount -1
				S.Position=i
				If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
					multiplicador = multiplicador +1
					PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
				Else
					PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
					multiplicador = multiplicador +1
					PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
'					LogColor(s.GetLong("L_CANT"),Colors.Magenta)
'					LogColor(s.GetLong("L_COSTOU"),Colors.Magenta)
'					LogColor(s.GetLong("L_COSTO_TOT"),Colors.Magenta)
					TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOU") + s.GetLong("L_COSTO_TOT")
					ESPACIO = 92
					BLANCO = " "
					ESPACIO = ESPACIO - TAMANO
					ESPACIO = ESPACIO / 2
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
					multiplicador = multiplicador +1
					PDF.outtext(1,pagina-multiplicador*6, s.GETSTRING("PE_CANT") & BLANCO & s.GETSTRING("PE_COSTOU") & BLANCO & s.GETSTRING("PE_COSTO_TOT"))
'					pdf.outtext(1,108-9*6,s.GETSTRING("PE_COSTOU"))

'					pdf.outtext(1,108-9*6,s.GETSTRING("PE_COSTO_TOT")  )
				End If
			Next
		PDF.outtext(1,108-9*6," " )
		End If
		s.Close
		s=skmt.ExecQuery2("select PE_PRONOMBRE, PE_CANT, length(pe_cant) as L_CANT, PE_COSTOU, length(PE_COSTOU) as L_COSTOU,PE_CANT * PE_COSTOU AS  PE_COSTO_TOT, length(PE_CANT * PE_COSTOU) as L_COSTO_TOT,PE_PROID, PE_CEDIS  FROM PEDIDO WHERE PE_FOLIO = ? AND LENGTH(PE_CEDIS) > 3  AND PE_CLIENTE IN (Select CUENTA from cuentaa) order by  PE_CEDIS, PE_COSTOU", Array As String("PREVENTA"))
		If S.RowCount>0 Then
			multiplicador = multiplicador +1
			PDF.outtext(1,pagina-multiplicador*6,"--------------------------PROMOS PREVENTA-------------------------------------")
			multiplicador = multiplicador +1
			PDF.outtext(1,pagina-multiplicador*6,"Cant.                                   Precio                                    Importe")
			multiplicador = multiplicador +1
			PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------")
			For i=0 To S.RowCount -1
				S.Position=i
				If s.GetString("PE_CEDIS") = s.GetString("PE_PROID") Then
					multiplicador = multiplicador +1
					PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE") )
				Else
					PDF.sFont(PDF.fontHelvetica,0,7,PDF.colorBlack)
					multiplicador = multiplicador +1
					PDF.outtext(1,pagina-multiplicador*6,s.GetString("PE_PRONOMBRE"))
					LogColor(s.GetLong("L_CANT"),Colors.Magenta)
					LogColor(s.GetLong("L_COSTOU"),Colors.Magenta)
					LogColor(s.GetLong("L_COSTO_TOT"),Colors.Magenta)
					TAMANO = s.GetLong("L_CANT") + s.GetLong("L_COSTOU") + s.GetLong("L_COSTO_TOT")
					ESPACIO = 92
					BLANCO = " "
					ESPACIO = ESPACIO - TAMANO
					ESPACIO = ESPACIO / 2
					For E=0 To ESPACIO -1
						BLANCO = " " & BLANCO
					Next
					PDF.sFont(PDF.fontHelvetica,0,10,PDF.colorBlack)
					multiplicador = multiplicador +1
					PDF.outtext(1,pagina-multiplicador*6, s.GETSTRING("PE_CANT") & BLANCO & s.GETSTRING("PE_COSTOU") & BLANCO & s.GETSTRING("PE_COSTO_TOT"))
				End If
			Next
		End If
		s.Close
'		multiplicador = multiplicador +1
'		pdf.outtext(1,pagina-multiplicador*6," " )
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6," " )
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------")
		s=skmt.ExecQuery2("select SUM(PE_COSTO_TOT) AS TOTAL FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_FOLIO = ?", Array As String("PREVENTA"))
		s.Position =0
		
		
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6,"Descuento:   $" & 150)
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6,"Total preventa:   $" & (s.GetString("TOTAL") -150))
		s.Close
		c= skmt.ExecQuery2("select sum(PE_CANT) as PC_NOART from PEDIDO where PE_CLIENTE in (Select CUENTA from cuentaa) AND PE_PROID NOT IN (SELECT CAT_PA_ID FROM PROMOS_COMP ) AND PE_FOLIO = ?", Array As String("PREVENTA"))
		C.Position=0
		multiplicador = multiplicador +1
		PDF.outtext(1,pagina-multiplicador*6,"Total articulos preventa:   " & c.GetString("PC_NOART") )
		c.Close
	End If
'	multiplicador = multiplicador +1
'	pdf.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"--------------------------ESTE TICKET NO ES UN ---------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"-------------------COMPROBANTE FISCAL, SOLO ES--------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"---------------------------------INFORMATIVO-----------------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------" )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6," " )
'	multiplicador = multiplicador +1
	PDF.outtext(1,pagina-multiplicador*6,"-----------------------------------------------------------------------------------------" )
'	'all combinations of font normal, bold,italic,underline and strikethrough
'	For i=0 To 15
'		'select a font
'		pdf.sFont(pdf.fontHelvetica,s,30,pdf.colorBlack)
'		'draw a text at position 20 (from left) and 277 (from bottom)
'		pdf.outtext(20,277-i*15,"Hello world!")
'	Next
	DateTime.DateFormat = "ddmmyyyy"
	DateTime.TimeFormat = "HHmmss"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	archivoTicketPDF = sDate&sTime&".pdf"
	'save to file with compression if data compressed are smaller
	savePDF(PDF, archivoTicketPDF, PDF.CompressAlways)
	'open with default viewer
'	openPDF(sDate&sTime&".pdf")
End Sub

private Sub savePDF(apdf As cPDF,afile As String,acompress As Int)
	Dim folder As String
	#if B4J
		folder=xui.DefaultFolder
	#End If
	#if B4A
	folder = Starter.fFileProvider.SharedFolder
	#End If
	#if B4I
	'......
	#End If
'	Log("aaa:" & folder)
'	Log("bbb:" & B4XPages.MainPage.Provider.SharedFolder)
	apdf.saveToFile(folder, afile, acompress)
End Sub

private Sub openPDF(afile As String)
	#if B4J
		fx.ShowExternalDocument(File.GetUri(xui.DefaultFolder,afile))
	#end if
	#if B4A
	Dim in As Intent
	in.Initialize(in.ACTION_VIEW, "")
	Starter.ffileProvider.SetFileUriAsIntentData(in, afile)
	in.SetComponent("android/com.android.internal.app.ResolverActivity")
	in.SetType("application/pdf")
	StartActivity(in)
	#end if
	#if B4I
	'......
	#End If
End Sub

Private Sub b_enviarTicket_Click
	et_numeroPDF.Text = telefono.trim
	p_transparentePDF.Visible = True
'	ProgressDialogShow("Enviando ticket, un momento por favor.")
'	Log("Progress 1")
'	PDFGENERAR
'	enviaTicket
'	Sleep(1500)
'	Guardar_Click
'	ProgressDialogHide
	Log("Progress 2")
End Sub

Private Sub b_enviarTicket_LongClick
'	et_numeroPDF.Text = TELEFONO.trim
'	p_transparentePDF.Visible = True
'	PDFGENERAR
'	EnviarPDFWhatsAppNumero(et_numeroPDF.Text)
'	Guardar_Click
End Sub

Sub enviaTicket
	'copy the shared file to the shared folder
	Sleep(1000)
	Dim email As Email
	email.To.Add("cheveguerra@gmail.com")
	email.Subject = "subject"
	email.Attachments.Add(Starter.fFileProvider.GetFileUri(archivoTicketPDF))
	Dim in As Intent = email.GetIntent
	in.Flags = 1 'FLAG_GRANT_READ_URI_PERMISSION
	StartActivity(in)
End Sub

Sub EnviarPDFWhatsAppNumero(NumeroTelefono As String)
	If NumeroTelefono.Length = 10 Then NumeroTelefono = "521" & NumeroTelefono ' Agregamos el 521 si es que falta.
	' Ruta del archivo PDF
'	Dim RutaArchivo As String = Starter.fFileProvider.SharedFolder & "/" & archivoTicketPDF
'	Log(RutaArchivo)

	' Verificar si el archivo existe
	If File.Exists(Starter.fFileProvider.SharedFolder, archivoTicketPDF) Then

		Dim fd As MultipartFileData
		fd.Initialize
		fd.KeyName = "file"
		fd.Dir = Starter.fFileProvider.SharedFolder
		fd.FileName = archivoTicketPDF
		fd.ContentType = "application/pdf"
		Private link As String = "http://keymon.net:9001/v1/ticketpdf"
		Private campos As Map = CreateMap( "message":"Tu compra de Guna va ser a *crédito* por el monto de $${NumberFormat2(monto, 1, 2, 2, True)}\n\nManda *1* para confirmar\nManda *0* para rechazar\n\n*Nota:* Si este mensaje no se contesta, se considerará que el pago es en *EFECTIVO*.\n\n(Solo el *número* por favor)")
		campos.Put("number", NumeroTelefono)
		Log(NumeroTelefono)
		campos.Put("message","Tu recibo")
		Log(campos)
		Private job As HttpJob
		job.Initialize("", Me)
		job.PostMultipart(link, campos, Array(fd))
'		job.GetRequest.SetContentType("application/json")
		Log(5555)
		Wait For (job) JobDone(job As HttpJob)

'		' Obtener el URI del archivo usando FileProvider
'		Dim Uri0 As Object = Starter.fFileProvider.GetFileUri(archivoTicketPDF)
'        
'		' Crear un Intent para compartir el archivo
'		Dim Intent1 As Intent
'		Intent1.Initialize(Intent1.ACTION_SEND, "")
'        
'		' Establecer el tipo MIME del archivo (PDF)
'		Intent1.SetType("application/pdf")
'        
'		' Agregar el URI del archivo al Intent
'		Intent1.PutExtra("android.intent.extra.STREAM", Uri0)
'        
'		' Establecer permisos de lectura para la aplicación que recibe el archivo
'		Intent1.Flags = 1 ' FLAG_GRANT_READ_URI_PERMISSION
'        
'		' Especificar el número de teléfono en el Intent
'		Intent1.PutExtra("jid", NumeroTelefono & "@s.whatsapp.net") ' Formato de WhatsApp
'        
'		' Especificar que se abra directamente en WhatsApp
'		Intent1.SetPackage("com.whatsapp")
'        
'		' Iniciar el Intent para compartir el archivo
'		Log("Intent para compartir archivo")
'		StartActivity(Intent1)
	Else
		ToastMessageShow("El archivo PDF no existe.", True)
	End If
End Sub

Sub EnviarPDFWhatsAppNumero2(NumeroTelefono As String)
	If NumeroTelefono.Length = 10 Then NumeroTelefono = "521" & NumeroTelefono ' Agregamos el 521 si es que falta.
    ' Ruta del archivo PDF
    Dim RutaArchivo As String = Starter.fFileProvider.SharedFolder & "/" & archivoTicketPDF
    Log(RutaArchivo)
    
    ' Verificar si el archivo existe
	If File.Exists(Starter.fFileProvider.SharedFolder, archivoTicketPDF) Then
        ' Paso 1: Abrir WhatsApp con el número específico
        Dim UriWhatsApp As String = "https://wa.me/" & NumeroTelefono
        Dim IntentWhatsApp As Intent
        IntentWhatsApp.Initialize(IntentWhatsApp.ACTION_VIEW, UriWhatsApp)
        
        ' Verificar si WhatsApp está instalado
'        If IntentWhatsApp.ResolveActivity(PackageManager) Is Nothing Then
'            ToastMessageShow("WhatsApp no está instalado.", True)
'            Return
'        End If
        
        ' Iniciar el Intent para abrir WhatsApp
        StartActivity(IntentWhatsApp)
        
        ' Paso 2: Mostrar un mensaje para compartir el archivo manualmente
        ToastMessageShow("Por favor, comparte el archivo manualmente en WhatsApp.", True)
        
        ' Esperar un momento para que WhatsApp se abra
        Sleep(3000)
        
        ' Paso 3: Compartir el archivo desde tu aplicación
		Dim Uri0 As Object = Starter.fFileProvider.GetFileUri(archivoTicketPDF)
        
        ' Crear un Intent para compartir el archivo
        Dim Intent1 As Intent
        Intent1.Initialize(Intent1.ACTION_SEND, "")
        
        ' Establecer el tipo MIME del archivo (PDF)
        Intent1.SetType("application/pdf")
        
        ' Agregar el URI del archivo al Intent
        Intent1.PutExtra("android.intent.extra.STREAM", Uri0)
        
        ' Establecer permisos de lectura para la aplicación que recibe el archivo
        Intent1.Flags = 1 ' FLAG_GRANT_READ_URI_PERMISSION
        
        ' Iniciar el Intent para compartir el archivo
        StartActivity(Intent1)
    Else
        ToastMessageShow("El archivo PDF no existe.", True)
    End If
End Sub

Private Sub b_envioPDF_Click
	If ALMACEN = 87 Or ALMACEN = 6 Then
		If Subs.traemontoprod Then
			PDFGENERAR2
		Else
			PDFGENERAR
		End If
	Else
		PDFGENERAR
	End If
	
	Sleep(3000)
	EnviarPDFWhatsAppNumero(et_numeroPDF.Text)

	B4XPages.MainPage.skmt.ExecNonQuery("delete from TICKET_IMPRESO where idCliente In (select cuenta from cuentaa)")
	B4XPages.MainPage.skmt.ExecNonQuery($"insert into TICKET_IMPRESO (idCliente) values ('${Subs.traeCliente}')"$)

	DateTime.DateFormat = "YYYY/MM/dd HH:mm:ss"
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "insertEnvioTicketPDF"
	Log(DateTime.Date(DateTime.Now))
	cmd.Parameters = Array As Object(Subs.traeCliente, Subs.traeUsuarioDeBD, et_numeroPDF.text, DateTime.Date(DateTime.Now))
	reqManager.ExecuteCommand(cmd , "insertEnvioTicketPDF")

	cmd.Initialize
	cmd.Name = "insertaTelefonoTicketPDF"
	Log(DateTime.Date(DateTime.Now))
	cmd.Parameters = Array As Object(Subs.traeAlmacen, Subs.traeRuta, Subs.traeCliente, et_numeroPDF.text)
	reqManager.ExecuteCommand(cmd , "insertTelefonoTicketPDF")

	Guardar_Click
	p_transparentePDF.Visible = False
End Sub

Private Sub b_cancelarEnvioPDF_Click
	p_transparentePDF.Visible = False
End Sub

Private Sub p_transparentePDF_Click
	
End Sub

Private Sub et_numeroPDF_TextChanged (Old As String, New As String)
	If New.Length = 10 Then b_envioPDF.Enabled = True Else b_envioPDF.Enabled = False
End Sub

Private Sub btnPlanLealtad_Click
	Subs.centraPanel(pnl_btns, pnlPlanLealtad.Width)
	pnlPlanLealtad.Visible = True
End Sub

Private Sub btnCancelarPlanLealtad_Click
	pnlPlanLealtad.Visible = False
End Sub

Private Sub btnAceptaPlanLealtad_Click
	
	c = Starter.skmt.ExecQuery("SELECT * FROM PLAN_LEALTAD WHERE PL_CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	c.Position = 0
	If c.RowCount = 0 Then
'		Starter.skmt.ExecNonQuery($"INSERT INTO PLAN_LEALTAD (PL_BANDERA,PL_CLIENTE) VALUES (1,'${cuenta}')"$)
		B4XPages.MainPage.skmt.ExecNonQuery($"insert into PLAN_LEALTAD (PL_BANDERA, PL_CLIENTE) values ('1','${Subs.traeCliente}')"$)
		pnlPlanLealtad.Visible = False
		Log("AQUI")
		B4XPage_Appear
	Else
		Starter.skmt.ExecNonQuery($"UPDATE PLAN_LEALTAD SET PL_BANDERA = 1 where PL_CLIENTE IN (SELECT CUENTA FROM CUENTAA)"$)
		pnlPlanLealtad.Visible = False
		Log("AQUI2")
		B4XPage_Appear
	End If
End Sub

'##########################  INICIA CODIGO PARA CREDITOS ####################
Sub mandaWAMsgCredito(numTel As String, monto As String)
	DateTime.DateFormat="MM/dd/yyyy HH:mm:ss"
	Private Fecha As String=DateTime.Date(DateTime.now)
	numTel = "521" & numTel
	Private numTel As String = "5215554192439"
'	Private monto As String = "1500"
	Private idCliente As String = Subs.traeCliente '"10748"
	Private ruta As String = Subs.traeRuta '"333"
	Private ALMACEN As String = Subs.traeAlmacen '"1"

'	CON POST
	Private link As String = "http://keymon.net:9000/v1/messages"
	Private elJSON As String = $"{
		"number":"${numTel}",
		"message":"Tu compra de Guna va ser a *crédito* por el monto de $${NumberFormat2(monto, 1, 2, 2, True)}\n\nManda *1* para confirmar\nManda *0* para rechazar\n\n*Nota:* Si este mensaje no se contesta, se considerará que el pago es en *EFECTIVO*.\n\n(Solo el *número* por favor)",
		"monto":"${monto}",
		"idcliente":"${idCliente}",
		"almacen":"${ALMACEN}",
		"ruta": "${ruta}",
		"fecha":"${Fecha}"
		}"$
	Private job As HttpJob
	job.Initialize("", Me)
	job.PostString(link, elJSON)
	job.GetRequest.SetContentType("application/json")
	Wait For (job) JobDone(job As HttpJob)

'	CON GET
'	Private retorno As String = "%0D%0A"
'	Private link As String = $"http://keymon.lat:9000/v1/messages?number=${numTel}&message=Tu compra de Guna va ser a crédito por el monto de $${NumberFormat2(monto, 1, 2, 2, True)}${retorno}${retorno}Manda *1* para confirmar${retorno}Manda *0* para rechazar${retorno}${retorno}*Nota: Si este mensaje no se contesta, se considerará que el pago es en EFECTIVO*${retorno}${retorno}(Solo el *número* por favor)&monto=${monto}&idcliente=${idCliente}&almacen=1&ruta=333&fecha=${Fecha}"$
'	Private job As HttpJob
'	job.Initialize("", Me)
	''	job.PostString(link, elJSON)
'	job.Download(link)
	''	job.GetRequest.SetContentType("application/json")
'	Wait For (job) JobDone(job As HttpJob)

	Log("Whatsapp enviado con exito: " & job.Success)
End Sub
'##########################  TERMINA CODIGO PARA CREDITOS ####################




Private Sub p_comentario_Click
	
End Sub

Private Sub p_comentarios_Click
	
End Sub

Private Sub b_comentarios_Click
	p_comentario.Visible = True
	et_comentario.Text = ""
	Dim label1 As Label
	label1 = lv_comentarios.SingleLineLayout.Label
	label1.TextSize = 16
	label1.TextColor = Colors.White
		
		
		

	label1.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)

	
'		Subs.centraListView(lv_comentarios,Root.Width)
	
	Private c As Cursor = Starter.skmt.ExecQuery("select COMENTARTIO FROM COMENTARIOS WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	lv_comentarios.SingleLineLayout.Label.TextColor = Colors.BlacK
	lv_comentarios.Clear
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount - 1
			c.Position = i
			Dim itemText As String
				
			itemText = $"${c.GetString("COMENTARTIO")}"$
			lv_comentarios.AddSingleLine(itemText)
			
		Next
	Else
		lv_comentarios.AddSingleLine("No hay datos disponibles.")
	End If
'	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS COMENTARIOS (COMENTARTIO TEXT, CLIENTE TEXT, DESCARGADO TEXT)")


End Sub

Private Sub b_cerarcom_Click
	p_comentario.Visible = False
	et_comentario.Text = ""
End Sub

Private Sub b_agregarcom_Click
	
	If et_comentario.Text <> "" Then
		If chb_com.Checked Then
			B4XPages.MainPage.skmt.ExecNonQuery($"insert into COMENTARIOS (COMENTARTIO, CLIENTE,comentario_tmp) values ('${et_comentario.Text}','${Subs.traeCliente}',1)"$)
		Else If chb_com.Checked = False Then
			B4XPages.MainPage.skmt.ExecNonQuery($"insert into COMENTARIOS (COMENTARTIO, CLIENTE,comentario_tmp) values ('${et_comentario.Text}','${Subs.traeCliente}',0)"$)
		End If
		
		Dim label1 As Label
		label1 = lv_comentarios.SingleLineLayout.Label
		label1.TextSize = 16
		label1.TextColor = Colors.White
		
		
		

		label1.Typeface = Typeface.CreateNew(Typeface.DEFAULT_BOLD, Typeface.STYLE_BOLD)

	
'		Subs.centraListView(lv_comentarios,Root.Width)
	
		Private c As Cursor = Starter.skmt.ExecQuery("select COMENTARTIO FROM COMENTARIOS WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		lv_comentarios.SingleLineLayout.Label.TextColor = Colors.BlacK
		lv_comentarios.Clear
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				Dim itemText As String
				
				itemText = $"${c.GetString("COMENTARTIO")}"$
				lv_comentarios.AddSingleLine(itemText)
			
			Next
		Else
			lv_comentarios.AddSingleLine("No hay datos disponibles.")
		End If
		c.Close
		et_comentario.Text = ""
	End If
	
End Sub

Private Sub Label19_Click
	Dim numeroTel As String = Label19.Text
    
	numeroTel = numeroTel.Replace(" ", "").Replace("-", "").Replace("(", "").Replace(")", "")
    
	If numeroTel.Length > 0 Then
		Dim Intent1 As Intent
		Intent1.Initialize("android.intent.action.DIAL", "tel:" & numeroTel)
		StartActivity(Intent1)
	Else
		ToastMessageShow("Número no válido", False)
	End If
    
	Return True
End Sub



Private Sub ImageView4_Click
	InitializeCamera2
	p_camara.Visible = True
	Subs.centraPanel(p_cam,p_camara.Width)
	
	p_camara.BringToFront
End Sub


Private Sub InitializeCamera2
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
	Wait For B4XPage_PermissionResult (Permission As String, resultC As Boolean)
	If resultC Then
		camEx.Initialize(p_cam, frontCamera, Me, "Camera1")
		frontCamera = camEx.Front
		Log("inicializamos Camara")
	Else
		ToastMessageShow("No permission Camara!!!", True)
	End If
End Sub

Sub Camera1_Ready (Success As Boolean)
	Log("Camara ready")
	If Success Then
		camEx.SetJpegQuality(90)
		camEx.SetContinuousAutoFocus
		camEx.CommitParameters
		camEx.StartPreview
		Log(camEx.GetPreviewSize)
	Else
		ToastMessageShow("Cannot open camera.", True)
		Log("Cannot open camera")
	End If
End Sub

Sub Camera1_PictureTaken (Data()As Byte)

	DateTime.DateFormat="ddMMyyyyHHmmss"
	nombrefoto = DateTime.Now & "_FOTO1.jpg"
	teclado.HideKeyboard
	fototomada = nombrefoto
		

	Log("tome foto")
	Dim filename As String = fototomada
	Dim Dirp As String = File.DirInternal
	Dim Dir As String
	Dim Dir2 As String
	Try
		File.MakeDir(Dirp,"/md")
		Dir = "/md"
		Log("creado en promotoria " & Dirp & Dir)
	Catch
		Dir = ""
		Log("creado en raiz")
	End Try
	
	Try
		File.MakeDir(Dirp & Dir,"/reduccion")
		Dir2 = "/reduccion"
		Log("creado en promotoria " & Dirp & Dir & Dir2)
	Catch
		Dir = ""
		Log("creado en raiz")
	End Try
	
	camEx.SavePictureToFile(Data, Dirp&Dir, filename)
	camEx.StartPreview 'restart preview
'	ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename, True)
	Log("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename)
	p_camara.Visible = False
	
	Log(nombrefoto)
	
	Dim img As B4XBitmap = xui.LoadBitmapResize(File.DirInternal & Dir, filename, 225, 300, True)
	Dim out As OutputStream = File.OpenOutput(File.DirInternal & Dir & Dir2, filename, False)
	img.WriteToStream(out, 100, "PNG")
'		foto4 = File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto3)
		
	out.Close
	ImageView4.Bitmap = LoadBitmap(File.DirInternal & Dir & Dir2,nombrefoto)

	skmt.ExecNonQuery2("UPDATE kmt_info3 SET foto = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto)))
	StopCamera2
	
End Sub

Private Sub p_camara_Click
	
End Sub

Private Sub b_foto_Click
'	Log(nombrefoto)
'	Dim Dirp As String = File.DirInternal
'	Dim Dir As String
'	Dim Dir2 As String
'	Try
'		File.MakeDir(Dirp,"/md")
'		Dir = "/md"
'		Log("creado en promotoria " & Dirp & Dir)
'	Catch
'		Dir = ""
'		Log("creado en raiz")
'	End Try
'	
'	Try
'		File.MakeDir(Dirp & Dir,"/reduccion")
'		Dir2 = "/reduccion"
'		Log("creado en promotoria " & Dirp & Dir & Dir2)
'	Catch
'		Dir = ""
'		Log("creado en raiz")
'	End Try
	camEx.TakePicture
	p_camara.Visible = False
	
'	skmt.ExecNonQuery2("UPDATE kmt_info3 SET foto = (?) WHERE CAT_CL_CODIGO IN (SELECT CUENTA FROM CUENTAA)",Array As Object(File.ReadBytes(File.DirInternal & Dir & Dir2, nombrefoto)))
'	StopCamera2
End Sub

Private Sub StopCamera2
'	Capturing = False
	If camEx.IsInitialized Then
		camEx.Release
	End If
End Sub

Private Sub p_cliente__Click
	
End Sub

Private Sub pnlPlanLealtad_Click
	
End Sub

Private Sub CH_FACTURA_CheckedChange(Checked As Boolean)
	
End Sub

Private Sub l_limite_Click
	
		
	Dim pagarepen As Cursor = B4XPages.MainPage.skmt.ExecQuery("select FECHA, SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If pagarepen.RowCount > 0 Then
		Dim cs As CSBuilder
		cs.Initialize
		p_deuda.Visible = True
		p_deuda.Width = Root.Width
		p_deuda.Height = Root.Height
		
		pagarepen.Position = 0
		DateTime.DateFormat="dd/MM/yyyy"
		Dim FechaInicio As String = pagarepen.GetString("FECHA")  ' Formato: dd/MM/yyyy
'		Dim FechaHoy As String = DateTime.Date(DateTime.Now)  ' Fecha actual en formato dd/MM/yyyy
		Log(pagarepen.GetString("FECHA"))
		
		' Convertir las fechas a milisegundos (desde 01/01/1970)
		Dim TicksInicio As Long = DateTime.DateParse(FechaInicio)
		Dim TicksHoy As Long = DateTime.DateParse(DateTime.Date(DateTime.Now))

		' Calcular diferencia en días
		Dim DiferenciaDias As Int = (TicksHoy - TicksInicio) / DateTime.TicksPerDay

		' Mostrar resultado
		Log($"Días transcurridos: ${DiferenciaDias}"$)
		
		c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_DIASCREDITO,0) AS CAT_CL_DIASCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position = 0

		If DiferenciaDias <= c.GetInt("CAT_CL_DIASCREDITO") + 8 Then
'			Msgbox2Async($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Recordatorio", "Ok", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
			
'			l_deuda.Text = ($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$)
			l_deuda.Text = cs.Color(Colors.Black).Append("Monto de la deuda:" & CRLF&CRLF).Pop.Size(18).Color(Colors.RGB(48,109,0)).Append("$ "& pagarepen.GetString("SALDO_PENDIENTE")).PopAll
		Else If DiferenciaDias > c.GetInt("CAT_CL_DIASCREDITO") + 8 Then
'			l_deuda.Text = ($"No se puede realizar venta por que presenta ${(DiferenciaDias-(c.GetInt("CAT_CL_DIASCREDITO") +1))} días de atraso en el credito, por un monto de $${pagarepen.GetString("SALDO_PENDIENTE")}"$)
			l_deuda.Text = cs.Color(Colors.Black).Append("Monto de la deuda:" & CRLF&CRLF).Pop.Color(Colors.Red).Size(18).Append("$ " &pagarepen.GetString("SALDO_PENDIENTE")&CRLF&CRLF).Pop.Size(14).Color(Colors.Black).Append("Dias de atraso:" & CRLF&CRLF).Pop.Size(18).Color(Colors.Red).Append((DiferenciaDias-(c.GetInt("CAT_CL_DIASCREDITO") +1))).PopAll
		End If
	Else
		p_deuda.Visible = True
		
		p_deuda.Width = Root.Width
		p_deuda.Height = Root.Height
		
		l_deuda.Text = "No tiene adeudo"
	End If

End Sub

Private Sub b_okdeuda_Click
	p_deuda.Visible = False
End Sub

Private Sub p_deuda_Click
	p_deuda.Visible = False
End Sub

Private Sub b_preventa2_Click
	'	Mejorar precisión antes de procesar la venta
'	MejorarPrecisionGPS
'	Sleep(500) ' Esperar un poco para que el GPS se estabilice
	B4XPages.MainPage.tipo_venta = "PREVENTA_FUTURA"
	Dim pagarepen As Cursor = B4XPages.MainPage.skmt.ExecQuery("select FECHA, SALDO_PENDIENTE FROM ABONOSP WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If pagarepen.RowCount > 0 Then
		pagarepen.Position = 0
		DateTime.DateFormat="dd/MM/yyyy"
		Dim FechaInicio As String = pagarepen.GetString("FECHA")  ' Formato: dd/MM/yyyy
'		Dim FechaHoy As String = DateTime.Date(DateTime.Now)  ' Fecha actual en formato dd/MM/yyyy
		Log(pagarepen.GetString("FECHA"))

		' Convertir las fechas a milisegundos (desde 01/01/1970)
		Dim TicksInicio As Long = DateTime.DateParse(FechaInicio)
		Dim TicksHoy As Long = DateTime.DateParse(DateTime.Date(DateTime.Now))

		' Calcular diferencia en días
		Dim DiferenciaDias As Int = (TicksHoy - TicksInicio) / DateTime.TicksPerDay

		' Mostrar resultado
		Log($"Días transcurridos: ${DiferenciaDias}"$)

		c=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_DIASCREDITO,0) AS CAT_CL_DIASCREDITO from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position = 0

		If DiferenciaDias <= c.GetInt("CAT_CL_DIASCREDITO") + 8 Then
'			MsgboxAsync($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Recordatorio")
			Msgbox2Async($"Favor de pagar su credito el día de mañana por un monto  de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Recordatorio", "Ok", "", "", LoadBitmap(File.DirAssets,"alert2.png"), False)
			Wait For Msgbox_Result (resultado As Int)
			If resultado = DialogResponse.POSITIVE Then
				gestionar
			End If
		Else If DiferenciaDias > c.GetInt("CAT_CL_DIASCREDITO") + 8 Then
			MsgboxAsync($"No se puede realizar venta por que presenta ${(DiferenciaDias-(c.GetInt("CAT_CL_DIASCREDITO") +1))} días de atraso en el credito, por un monto de $${pagarepen.GetString("SALDO_PENDIENTE")}"$, "Atención")
		End If
	Else
		gestionar
	End If
End Sub

Private Sub l_atiende_LongClick
	p_atiende.Height = Root.Height
	p_atiende.Width = Root.Width
	p_atiende.Visible = True
End Sub

Private Sub b_acepatiende_Click
	If et_atiende.Text <> "" Then
		
		Private coord As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT * from ATIENDE where CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		
		If coord.RowCount = 0 Then
			skmt.ExecNonQuery2("INSERT INTO ATIENDE(ATIENDE,CLIENTE) VALUES (?,?)", Array As String (et_atiende.Text,Subs.traeCliente))
			B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE kmt_info3 set CAT_CL_ATIENDE1 = '${et_atiende.Text}'  where CAT_CL_CODIGO In (select cuenta from cuentaa)"$)
			MsgboxAsync("Datos actualizados.","Atención")
			l_atiende.Text = et_atiende.Text
			ime.HideKeyboard
			p_atiende.Visible = False
			et_atiende.Text = ""
		Else
			skmt.ExecNonQuery2("UPDATE ATIENDE SET ATIENDE = ? where CLIENTE IN (SELECT CUENTA FROM CUENTAA)", Array As String (et_atiende.Text))
			B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE kmt_info3 set CAT_CL_ATIENDE1 = '${et_atiende.Text}'  where CAT_CL_CODIGO In (select cuenta from cuentaa)"$)
			MsgboxAsync("Datos actualizados.","Atención")
			l_atiende.Text = et_atiende.Text
			ime.HideKeyboard
			p_atiende.Visible = False
			et_atiende.Text = ""
		End If
		
		
	Else
		MsgboxAsync("Por favor captura un nombre valido.","Atención")
	End If
End Sub

Private Sub b_cancelatiende_Click
	p_atiende.Visible = False
	et_atiende.Text = ""
	ime.HideKeyboard
End Sub

Private Sub p_atiende_Click
	
End Sub

Private Sub Label19_LongClick
	p_telefono.Height = Root.Height
	p_telefono.Width = Root.Width
	p_telefono.Visible = True
	

End Sub

Private Sub b_aceptelefono_Click
	If et_telefono.Text <> "" Then
		If et_telefono.Text.Length = 10 Then
		
			Private coord As Cursor = B4XPages.MainPage.skmt.ExecQuery("SELECT * from TELEFONO where CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
		
			If coord.RowCount = 0 Then
				skmt.ExecNonQuery2("INSERT INTO TELEFONO(TELEFONO,CLIENTE) VALUES (?,?)", Array As String (et_telefono.Text,Subs.traeCliente))
				B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE kmt_info3 set CAT_CL_TELEFONO = '${et_telefono.Text}'  where CAT_CL_CODIGO In (select cuenta from cuentaa)"$)
				MsgboxAsync("Datos actualizados.","Atención")
				Label19.Text = et_telefono.Text
				ime.HideKeyboard
				p_telefono.Visible = False
				et_telefono.Text = ""
			Else
				skmt.ExecNonQuery2("UPDATE TELEFONO SET TELEFONO = ? where CLIENTE IN (SELECT CUENTA FROM CUENTAA)", Array As String (et_telefono.Text))
				B4XPages.MainPage.skmt.ExecNonQuery($"UPDATE kmt_info3 set CAT_CL_TELEFONO = '${et_telefono.Text}'  where CAT_CL_CODIGO In (select cuenta from cuentaa)"$)
				MsgboxAsync("Datos actualizados.","Atención")
				Label19.Text = et_telefono.Text
 
 				ime.HideKeyboard
				p_telefono.Visible = False
				et_telefono.Text = ""
			End If
		
		Else
			MsgboxAsync("Por favor captura un numero de teléfono valido.","Atención")
		End If
	Else
		MsgboxAsync("Por favor captura un numero de teléfono valido.","Atención")
	End If
End Sub

Private Sub b_canceltelefono_Click
	p_telefono.Visible = False
	et_telefono.Text = ""
	ime.HideKeyboard
End Sub

Private Sub p_telefono_Click
	
End Sub

Private Sub chb_com_CheckedChange(Checked As Boolean)
	
End Sub

Sub P_Imagengrande_click
	P_Imagengrande.Visible = False
End Sub

Private Sub ImageView4_LongClick
	Private fotomostrar As Cursor = Starter.skmt.ExecQuery("SELECT FOTO FROM FOTOS where CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
	If fotomostrar.RowCount > 0 Then
		
		fotomostrar.Position = 0
		Private fotomostrarfinal() As Byte = fotomostrar.GetBlob("FOTO")
		Dim InputStream1 As InputStream
		InputStream1.InitializeFromBytesArray(fotomostrarfinal, 0, fotomostrarfinal.Length)
		Dim Bitmap1 As Bitmap
		Bitmap1.Initialize2(InputStream1)
		InputStream1.Close
		I_fotogrande.Bitmap = Bitmap1
		Log("aqui si hay foto")
	Else
		I_fotogrande.Bitmap = LoadBitmap(File.DirAssets,"images.png")
		Log("aqui no hay foto")
	End If
	P_Imagengrande.Visible = True
End Sub

Private Sub b_guadarenc_Click
	DateTime.DateFormat = "dd/MM/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	Dim coloressaldo As Cursor=B4XPages.MainPage.skmt.ExecQuery("select IFNULL(CAT_CL_CLASIFICADOR5,0) AS CAT_CL_CLASIFICADOR5 from kmt_info3 where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	If coloressaldo.RowCount > 0 Then
		coloressaldo.Position = 0
		If coloressaldo.GetString("CAT_CL_CLASIFICADOR5") = "1" Then
			If e_1 <> "Selecciona una opcion" And e_2 <> "Selecciona una opcion" And e_3<> "Selecciona una opcion" And e_4 <> "Selecciona una opcion" And e_5 <> "Selecciona una opcion" Then
				B4XPages.MainPage.skmt.ExecNonQuery($"insert into ENCUESTAS_BAT (CLIENTE, RUTA, ALMACEN, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10,FECHA) values ('${Subs.traeCliente}', '${Subs.traeRuta}', '${Subs.traeAlmacen}', '${e_1}', '${e_2}', '${e_3}', '${e_4}', '${e_5}', 'N/A', 'N/A', 'N/A', 'N/A', 'N/A' , '${sDate}')"$)
				scv_bat.Visible = False
				
				' ENCUESTAS BAT
				c=B4XPages.MainPage.skmt.ExecQuery("SELECT * FROM ENCUESTAS_BAT WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
				If c.RowCount>0 Then
					For i=0 To c.RowCount -1
						c.Position=i
						Dim cmd As DBCommand
						cmd.Initialize
						cmd.Name = "insert_encuestas_bat_guna"
						cmd.Parameters = Array As Object(c.GetString("CLIENTE"),c.GetString("RUTA"),c.GetString("ALMACEN"),c.GetString("FECHA"),c.GetString("P1"),c.GetString("P2"),c.GetString("P3"),c.GetString("P4"),c.GetString("P5"),c.GetString("P6"),c.GetString("P7"),c.GetString("P8"),c.GetString("P9"),c.GetString("P10"))
						B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "INSENCUESTAS")
					Next
				End If
				c.Close
				vent
			Else
				MsgboxAsync("Favor de responder todas las preguntas","Atención")
			End If
		Else If coloressaldo.GetString("CAT_CL_CLASIFICADOR5") = "5" Then
			If e_1 <> "Selecciona una opcion" And e_2 <> "Selecciona una opcion" And e_3<> "Selecciona una opcion" And e_4 <> "Selecciona una opcion" And e_5 <> "Selecciona una opcion" And e_6 <> "Selecciona una opcion" And e_7 <> "Selecciona una opcion" And e_8<> "Selecciona una opcion" And e_9 <> "Selecciona una opcion" And e_10 <> "Selecciona una opcion" Then
				B4XPages.MainPage.skmt.ExecNonQuery($"insert into ENCUESTAS_BAT (CLIENTE, RUTA, ALMACEN, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10,FECHA) values ('${Subs.traeCliente}', '${Subs.traeRuta}', '${Subs.traeAlmacen}', '${e_1}', '${e_2}', '${e_3}', '${e_4}', '${e_5}', '${e_6}', '${e_7}', '${e_8}', '${e_9}', '${e_10}' , '${sDate}')"$)
				scv_bat.Visible = False
				
				' ENCUESTAS BAT
				c=B4XPages.MainPage.skmt.ExecQuery("SELECT * FROM ENCUESTAS_BAT WHERE CLIENTE IN (SELECT CUENTA FROM CUENTAA)")
				If c.RowCount>0 Then
					For i=0 To c.RowCount -1
						c.Position=i
						Dim cmd As DBCommand
						cmd.Initialize
						cmd.Name = "insert_encuestas_bat_guna"
						cmd.Parameters = Array As Object(c.GetString("CLIENTE"),c.GetString("RUTA"),c.GetString("ALMACEN"),c.GetString("FECHA"),c.GetString("P1"),c.GetString("P2"),c.GetString("P3"),c.GetString("P4"),c.GetString("P5"),c.GetString("P6"),c.GetString("P7"),c.GetString("P8"),c.GetString("P9"),c.GetString("P10"))
						B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "INSENCUESTAS")
					Next
				End If
				vent
			Else
				MsgboxAsync("Favor de responder todas las preguntas","Atención")
			End If
		End If
	End If
End Sub

Private Sub b_cancelencu_Click
	scv_bat.Visible = False
End Sub

Private Sub cb_p10_SelectedIndexChanged (Index As Int)
	e_10 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p9_SelectedIndexChanged (Index As Int)
	e_9 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p8_SelectedIndexChanged (Index As Int)
	e_8 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p7_SelectedIndexChanged (Index As Int)
	e_7 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p6_SelectedIndexChanged (Index As Int)
	e_6 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p5_SelectedIndexChanged (Index As Int)
	e_5 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p4_SelectedIndexChanged (Index As Int)
	e_4 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p3_SelectedIndexChanged (Index As Int)
	e_3 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p2_SelectedIndexChanged (Index As Int)
	e_2 = Sender.As(B4XComboBox).SelectedItem
End Sub

Private Sub cb_p1_SelectedIndexChanged (Index As Int)
	e_1 = Sender.As(B4XComboBox).SelectedItem
End Sub