B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=9.85
@EndOfDesignText@
#Region Shared Files
'#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
	'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
	'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip
	'###########################################################################################################
	'######################           PULL         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
	'###########################################################################################################
	'######################           PUSH         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=github&Args=..\..\
	'###########################################################################################################
	'######################      PUSH TORTOISE GIT     #########################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"./../../"&Args=/closeonend:2
	'###########################################################################################################
#End Region

'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=github&Args=..\..\

Sub Class_Globals
	Private Root As B4XView
	Private xui As XUI
	Public login As B4XMainPage
	Dim rp As RuntimePermissions
	Public principal As C_Principal
	Public clientes As C_Clientes
	Public cliente As C_Cliente
	Public productos As C_Productos
	Public updateAvailable As C_updateAvailable
	Public mapas As C_Mapas
	Public nuevoCliente As C_NuevoCliente
	Public ticketsDia As C_TicketsDia
	Public noVenta As C_NoVenta
	Public nota As C_Nota
	Public pedidos As C_Pedidos
	Public promos As C_Promos
	Public historico As C_Historico
	Public checklist As C_CheckList
	Dim kh As kms_helperSubs
	Dim ime As IME

	Dim reqManager As DBRequestManager
	Dim ultimaActualizacionGPS As String = 235959
	Dim almacen, ruta As String
	Dim user As EditText
	Dim pass As EditText
	Dim c As Cursor
	Dim D As Cursor
	Dim existe As String
	Dim paso1 As String
	Dim IMEI As String
	Dim alterno As String
	Private b_menu As Button
'	Dim PopupMenu As RSPopupMenu
	Dim cmd As DBCommand

	Private IMEN As EditText
	Private Entrar As Button
	Private Panel1 As Panel
	Private i_engranes As ImageView
	Private E_SERVER As EditText
	Private B_SERVER As Button
	Private B_MACIMP As Button
	Private CUANTOS As String
	Private foto_g () As Byte

	Private ListView1 As ListView
	Private ImageView1 As ImageView
	Private Label1 As Label
	Private B_BorrarFinDia As Button
	Private b_fdCancelar As Button
	Private b_findiaOk As Button
	Private p_finDia As Panel
	Private et_autSup As EditText

	'prueba downloadfile
	Dim ProgressBar1 As ProgressBar
	Dim Label1 As Label
	Dim btnDownload As Button
	Dim btnCancel As Button
	Private p_download As Panel
	Private Label6 As Label
	Dim logger As Boolean = True

	Dim lat_gps, lon_gps As String
	Dim tipo_venta As String
	Dim bTerminarClicked As Boolean = False
	Private lv_server As ListView
	Private l_server As Label
	Public rutaBDBackup As String = ""
	Private b_envioBD As Button
	Dim MES1 As ManageExternalStorage
	Dim device As Phone
	Private b_cargaLocal As Button
	Private p_cargaLocal As Panel
	Private et_cargaLocal As EditText
	Private b_cargaLocalOk As Button
	Private b_cargaLocalCancelar As Button
	Private p_botones As Panel
	Private b_importarBD As Button
	Private cb_geocerca As CheckBox
	Private p_extras As Panel
	Private et_geocerca As EditText
	Private b_extras As Button
	Private l_geocerca As Label
	Private b_aceptarExtras As Button
	Private cb_cartaPorte As CheckBox
	Private l_cartaPorte As Label
	Private et_maxClientesNuevos As EditText
	Private l_maxClientesNuevos As Label
	Dim in As Intent
	Dim intentUsado As Boolean = False
	Private p_importarBDWA As Panel
	Private cb_importarBDWA As CheckBox
End Sub

Public Sub Initialize
	B4XPages.GetManager.LogEvents = True
	kh.Initialize(Me, "kh", Starter.skmt)
	#if not(DEBUG)
		Starter.logger = False
	#end if
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	If Not(Starter.Logger) Then logger = False
	Dim sDate, sTime As String
	DateTime.DateFormat = "yyyyMMdd"
	sDate=DateTime.Date(DateTime.Now)
	Starter.skmt.ExecNonQuery("DROP TABLE IF EXISTS PEDIDO3")
	Starter.skmt.ExecNonQuery("CREATE TABLE PEDIDO3 (PE_PRECIO2 TEXT,PE_TIPO TEXT,PE_FOLIO NUMERIC,PE_DESC NUMERIC,PE_COSTO_SIN TEXT,PE_RUTA TEXT,PE_CEDIS TEXT,PE_COSTO_TOT NUMERIC,PE_COSTOU NUMERIC,PE_CANT NUMERIC,PE_PRONOMBRE TEXT,PE_PROID TEXT,PE_CLIENTE TEXT,PE_FECHA TEXT,PE_USUARIO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PEDIDO_SUGERIDO (ID_PRODUCTO TEXT, PROMEDIO TEXT, RUTA TEXT, ALMACEN TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS DESC_CLIENTES (DC_CL_CLIENTE TEXT, CAT_CL_DESCUENTO_SS TEXT, CAT_CL_DESCUENTO_RTEC TEXT, CAT_CL_DESCUENTO_PING TEXT, CAT_CL_TIPOCLIENTE TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA (HE_CLIE TEXT, HE_RES TEXT, HE_FECHA TEXT, HE_TIPO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_DESCUENTOS_SKU (CAT_DS_CLIENTE TEXT, CAT_DS_PRODID TEXT, CAT_DS_PORCENTAJE TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENVIOS (HE_FECHA TEXT, HE_CUANTOS TEXT, HE_TIPO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_ENCUESTA_PREGUNTA (CAT_EP_ID TEXT,CAT_EP_IDTIPOPREGUNTA TEXT,CAT_CE_DESCRIPCION TEXT,CAT_EP_PREGUNTA TEXT,CAT_EP_RES1_PRED TEXT,CAT_EP_RES2_PRED TEXT,CAT_EP_RES3_PRED TEXT,CAT_EP_ORDEN_PREGUNTA TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_FOTOS (HF_FOTO BLOB, HF_CUENTA TEXT, HF_IDENCUESTA TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CLIENTE_IMPRESO (CI_CUENTA TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CLIENTE_CANT_PROMOS (HCCP_CLIENTE TEXT, HCCP_PROMO TEXT, HCCP_CANT TEXT, HCCP_CANT_VENDIDA TEXT)")
	kh.agregaColumna(Starter.skmt, "HIST_CLIENTE_CANT_PROMOS", "HCCP_CANT_VENDIDA", "TEXT")
	kh.agregaColumna(Starter.skmt, "kmt_info", "CAT_CL_LIMITECREDITO", "TEXT")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_PROMO_MONTO (CPM_IDPROMO TEXT, CPM_MONTO TEXT, CPM_PROID TEXT, CPM_CLIENTE TEXT, CPM_CANT TEXT, CPM_RANGO TEXT, CPM_DESC TEXT)")
	Starter.skmt.ExecNonQuery2("INSERT INTO HIST_ENVIOS VALUES (?,0,?)", Array As Object(sTime, "PEDIDO"))
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_EXHIBIDORES2 (HIST_EX_ID_CLIENTE TEXT, HIST_EX_TIPO TEXT, HIST_EX_CANT TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_PROMO_WHATS(HIST_CLIENTE TEXT, HIST_RESPUESTA_PROMO)")
'	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_RMI(CAT_GP_ID TEXT,CAT_GP_NOMBRE TEXT,CAT_GP_PRECIO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_RMI(CAT_ID TEXT, CAT_DESCRIPCION TEXT, CAT_MONTO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS BITACORAGPS(fechab TEXT, usuariob TEXT, almacenb TEXT, rutab TEXT, eventob TEXT, clienteb TEXT, iniciob TEXT, finb TEXT, latitudb TEXT, longitudb TEXT, precision TEXT, motivonoventa TEXT, motivonovisita TEXT)")
	''' PARA LO DE DOE---
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD_DOE (CAT_GP_ID TEXT,CAT_GP_NOMBRE TEXT,CAT_GP_IMP1 TEXT,CAT_GP_IMP2 TEXT,CAT_GP_PRECIO TEXT,CAT_GP_CLASIF TEXT,CAT_GP_STS TEXT,CAT_GP_TIPO TEXT,CAT_GP_SUBTIPO TEXT,CAT_GP_IMG TEXT,CAT_GP_ALMACEN TEXT,CAT_GP_TIPOPROD TEXT,CAT_GP_INICIATIVA TEXT,CAT_GP_DEV TEXT,CAT_GP_CODPROMO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PEDIDO_DOE (PE_PRECIO2 TEXT,PE_TIPO TEXT,PE_FOLIO NUMERIC,PE_DESC NUMERIC,PE_COSTO_SIN TEXT,PE_RUTA TEXT,PE_CEDIS TEXT,PE_COSTO_TOT NUMERIC,PE_COSTOU NUMERIC,PE_CANT NUMERIC,PE_PRONOMBRE TEXT,PE_PROID TEXT,PE_CLIENTE TEXT,PE_FECHA TEXT,PE_USUARIO TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PEDIDOS_DOE_ENTREGA (PC_CLIENTE TEXT, PC_ENTREGA TEXT)")
	''' FIN DOE
	kh.agregaColumna(Starter.skmt, "kmt_info", "IMPRESION", "INTEGER")
	kh.agregaColumna(Starter.skmt, "USUARIOA", "FECHA", "TEXT")
	kh.agregaColumna(Starter.skmt, "PROMOS_COMP", "CAT_PA_PRECIO2", "TEXT")
	kh.agregaColumna(Starter.skmt, "PROMOS_COMP", "CAT_PA_TIPO_PROMONTO", "TEXT")
	kh.agregaColumna(Starter.skmt, "CAT_GUNAPROD", "CAT_GP_TIPOPROD2", "TEXT")
	kh.agregaColumna(Starter.skmt, "CAT_GUNAPROD2", "CAT_GP_TIPOPROD2", "TEXT")
	Root = Root1
'	Root.LoadLayout("MainPage")
	Root.LoadLayout("login")
	B4XPages.SetTitle(Me, "Kelloggs Preventa")
	login.Initialize
	B4XPages.AddPage("Login", login)
	principal.Initialize
	B4XPages.AddPage("Principal", principal)
	clientes.Initialize
	B4XPages.AddPage("Clientes", clientes)
	cliente.Initialize
	B4XPages.AddPageAndCreate("Cliente", cliente)
	productos.Initialize
	B4XPages.AddPage("Productos", productos)
	updateAvailable.Initialize
	B4XPages.AddPage("updateAvailable", updateAvailable)
	mapas.Initialize
	B4XPages.AddPage("Mapas", mapas)
	nuevoCliente.Initialize
	B4XPages.AddPageAndCreate("NuevoCliente", nuevoCliente)
	ticketsDia.Initialize
	B4XPages.AddPage("TicketsDia", ticketsDia)
	noVenta.Initialize
	B4XPages.AddPage("NoVenta", noVenta)
	nota.Initialize
	B4XPages.AddPage("Nota", nota)
	pedidos.Initialize
	B4XPages.AddPage("Pedidos", pedidos)
	promos.Initialize
	B4XPages.AddPage("Promos", promos)
	historico.Initialize
	B4XPages.AddPage("Historico", historico)
	checklist.Initialize
	B4XPages.AddPage("CheckList", checklist)
	Panel1.Top = 0 : Panel1.left = 0
	ruta = Starter.ruta
	Starter.tiempos.Initialize
	kh.guardaAppInfo

	'Revisamos si se disparo el intent de cargar la base de datos desde WhatApp.
	If kh.traeUsarIntentBDWA Then kh.importaBDDesdeWhatsApp

'	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna "IMPRESION" en la tabla
'		c=Starter.skmt.ExecQuery("SELECT COUNT(*) AS fCol FROM pragma_table_info('kmt_info') WHERE name='IMPRESION'")
'		c.Position = 0
'		If c.GetString("fCol") = 0 Then 'Si no esta la columna FECHA la agregamos
'			Starter.skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN IMPRESION INTEGER")
'		End If
'	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
'		Try
'			Starter.skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN IMPRESION INTEGER")
'		Catch
'			Log(LastException)
'		End Try
'	End Try
'	Try 'Agregamos columna fecha a usuarioa
'		c=Starter.skmt.ExecQuery("SELECT fecha FROM usuarioa")
'	Catch
'		LogColor("Agregamos columna fecha a usuarioa", Colors.red)
'		Starter.skmt.ExecNonQuery("ALTER TABLE usuarioa ADD COLUMN FECHA TEXT")
'	End Try
'	If sDate = "20190523" Then
'		Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER"))
'		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER", Starter.DBReqServer))
'	End If
'	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("ULTIMOMODULO"))
'	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("ULTIMOMODULO", "MAIN"))
	c = Starter.skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
	c.Position = 0
	If c.GetString("CUANTOS") = 0 Then
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER", Starter.DBReqServer))
'	Else
'		c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
'		c.Position = 0
'		Starter.server = c.GetString("CAT_VA_VALOR")
'		reqManager.Initialize(Me, Starter.server)
	End If
'	reqManager.Initialize(Me, Starter.server)
'	Activity.LoadLayout("login")
	Label1.Text = Application.VersionName
	
'	Log("Pedimos permisos de almacenamiento externo")
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then Log("Tenemos permisos de escritura externa.")
	c = Starter.skmt.ExecQuery("SELECT COUNT(*) as CUANTOS FROM TMP_INSPECCION_AUTO_DIARIA")
	c.Position = 0
	CUANTOS = c.GetString("CUANTOS")
	c.Close
	If CUANTOS = 0 Then
		Dim theDir As String
		If File.IsDirectory("/","kmts") Then
			theDir = "/kmts"
		End If
		Try
			File.MakeDir(File.DirInternal,"kmts")
			theDir = "/kmts"
		Catch
			theDir = ""
		End Try
		Try
			foto_g = Bit.InputStreamToBytes(File.OpenInput(File.DirAssets, "vista1.png"))
			Dim SALIDA As OutputStream
			SALIDA = File. OpenOutput (File.DirInternal&theDir, "FOTO1.jpg", False)
			SALIDA.WriteBytes(foto_g, 0, foto_g.Length)
			SALIDA.Close
'			If Logger Then LogColor("** ** Creamos FOTO1.jpg en "&File.DirInternal, Colors.Blue)
		Catch
			Msgbox("No se puede crear el archivo de foto","Aviso") 'ignore
		End Try
		Try
			foto_g = Bit.InputStreamToBytes(File.OpenInput(File.DirAssets, "vista3.png"))
			Dim SALIDA As OutputStream
			SALIDA = File. OpenOutput (File.DirInternal&theDir, "FOTO2.jpg", False)
			SALIDA.WriteBytes(foto_g, 0, foto_g.Length)
			SALIDA.Close
		Catch
			Msgbox("No se puede crear el archivo de foto","Aviso") 'ignore
		End Try
		Try
			foto_g = Bit.InputStreamToBytes(File.OpenInput(File.DirAssets, "vista2.png"))
			Dim SALIDA As OutputStream
			SALIDA = File. OpenOutput (File.DirInternal&theDir, "FOTO3.jpg", False)
			SALIDA.WriteBytes(foto_g, 0, foto_g.Length)
			SALIDA.Close
		Catch
			Msgbox("No se puede crear el archivo de foto","Aviso") 'ignore
		End Try
		Try
			foto_g = Bit.InputStreamToBytes(File.OpenInput(File.DirAssets, "vista4.png"))
			Dim SALIDA As OutputStream
			SALIDA = File. OpenOutput (File.DirInternal&theDir, "FOTO4.jpg", False)
			SALIDA.WriteBytes(foto_g, 0, foto_g.Length)
			SALIDA.Close
		Catch
			Msgbox("No se puede crear el archivo de foto","Aviso") 'ignore
		End Try
	End If
'	Dim ph As Phone 'Get Id Device
'	Dim DeviceID As String = Starter.ph.GetSettings("android_id").ToUpperCase
'	If logger Then Log($"Marca: ${Starter.ph.manufacturer}, Modelo: ${Starter.ph.model}"$)
'	If logger Then LogColor($"//////////////////   DeviceID: ${DeviceID} ////////////////// "$, Colors.Blue)
'	If Logger Then LogColor("Revisa permisos Phone_State", Colors.Green)
	'este codigo es para lo del menu
'	PopupMenu.Initialize("PopupMenu", b_menu)
'	PopupMenu.AddMenuItem(0, 0, "View")
'	PopupMenu.AddMenuItem(1, 1, "Edit")
'	PopupMenu.AddMenuItem(2, 2, "Details")
'	PopupMenu.AddMenuItem(3, 3, "Remove")
	' menu fin
'	Subs.borraArribaDe100Errores
'	Log("Pedimos permisos de estado del cel")
'	rp.CheckAndRequest(rp.PERMISSION_READ_PHONE_STATE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
''		Dim Phn As PhoneId
'		IMEN.Text = "" 'Phn.GetDeviceId
'		IMEI ="" ' Phn.GetDeviceId
'		If logger Then LogColor($"//////////////////  IMEI: ${IMEI} ////////////////// "$, Colors.Blue)
'	End If
'	Log("Permisos cel terminados")
	IMEN.Text = ""
	IMEI ="" ' Phn.GetDeviceId

	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For B4XPAge_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		StartService(Tracker)
		If logger Then Log("Start Tracker")
	Else
		ToastMessageShow("Sin permisos para GPS", True)
	End If
	MES1.Initialize(Me, "MES1")
'	Log("SDK: " & device.SdkVersion)
'	Get the device SDK version
	Dim SdkVersion As Int = device.SdkVersion
	' Choose which permission to request in order to access external storgage
	If SdkVersion < 30 Then
		Log("SDK = " & SdkVersion & " : Requesting WRITE_EXTERNAL_STORAGE permission")
		Dim rp As RuntimePermissions
		rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE) ' Implicit read capability if granted
		Wait For B4XPage_PermissionResult (Permission As String, ResultY As Boolean)
		Log($"PERMISSION_WRITE_EXTERNAL_STORAGE = ${ResultY}"$)
		Log("SDK = " & SdkVersion & " : Requesting READ_EXTERNAL_STORAGE permission")
		Dim rp As RuntimePermissions
		rp.CheckAndRequest(rp.PERMISSION_READ_EXTERNAL_STORAGE) ' Implicit read capability if granted
		Wait For B4XPage_PermissionResult (Permission As String, ResultX As Boolean)
		Log($"PERMISSION_READ_EXTERNAL_STORAGE = ${ResultX}"$)
	Else
		Log("SDK = " & SdkVersion & " : Requesting MANAGE_EXTERNAL_STORAGE permission")
		Log("On Entry MANAGE_EXTERNAL_STORAGE = " & MES1.HasPermission)
		If Not(MES1.HasPermission) Then
			MsgboxAsync("This app requires access to all files, please enable the option", "Manage All Files")
			Wait For Msgbox_Result(Res As Int)
			Log("Getting MES permission")
			MES1.GetPermission
			Wait For MES_StorageAvailable
		End If
	End If
	
'	Log("Permisos BT: " & rp.Check("android.permission.BLUETOOTH_CONNECT"))
'	Log("REVISAMOS PERMISOS DE BT")
'	rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT")
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then Log("Tenemos permisos de bluetooth.")
'	Log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
'	Log("Check phone state: " & rp.Check(rp.PERMISSION_READ_PHONE_STATE))
	kh.centraPanel(p_botones, Root.Width)
End Sub

Sub B4XPage_Appear
	If MES1.IsInitialized Then
		LogColor(MES1.HasPermission, Colors.Magenta)
		If MES1.HasPermission Then kh.revisaSiExisteRespaldo
	End If
	kh.RD_Init
	kh.SetButtonTintList(cb_geocerca, Colors.LightGray, Colors.RGB(43, 154, 211))
	kh.SetButtonTintList(cb_cartaPorte, Colors.LightGray, Colors.RGB(43, 154, 211))
	cb_geocerca.Checked = kh.traeUsarGeocerca
	cb_cartaPorte.Checked = kh.traeUsarCartaPorte
'	Log("LLAMAMOS traeUsarIntentBDWA")
	cb_importarBDWA.Checked = kh.traeUsarIntentBDWA
	et_maxClientesNuevos.Text = kh.traeMaxClientesNuevos
'	server = "http://keymon.com.mx:1782"
'	server = "http://201.99.139.28:1782"
'	server = "http://177.244.63.54:1782"
	reqManager.Initialize(Me, Starter.DBReqServer)
	Starter.montoActual = 0
	Starter.clientesTotal = 0
	Starter.clientesVenta =  0
	Starter.clientesVisitados = 0
	almacen = 0
	Starter.rutaPreventa =  0
	Starter.CANTIDADPROD = 0
	c.Close
	c = Starter.skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("CODIGO"))
	c.Position = 0
	CUANTOS = c.GetString("CUANTOS")
	c.Close
	If CUANTOS > 0 Then
		c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("CODIGO"))
		c.Position = 0
		If c.GetString("CAT_VA_VALOR") = "743" Then
			Entrar.Visible = True
		End If
		c.Close
	Else
		Log("INSERTAMOS CODIGO EN CAT_VARIABLES")
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("CODIGO","743"))
	End If
	c = Starter.skmt.ExecQuery2("select COUNT(*) AS CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("MACIMP"))
	c.Position = 0
	If c.GetString("CUANTOS") = 0 Then
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("MACIMP","0"))
	End If
	D = Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from version")
	D.Position = 0
	If D.GetString("CUANTOS") > 0 Then
		c = Starter.skmt.ExecQuery("select NOVERSION from version")
		c.Position = 0
		If c.GetString("NOVERSION") = "2.1" Then
			Starter.skmt.ExecNonQuery("delete from VERSION")
		End If
		c.Close
	End If
	D.Close
	D = Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from version")
	D.Position = 0
'	If D.GetString("CUANTOS") > 0 Then
'		c = Starter.skmt.ExecQuery("select NOVERSION from version")
'		c.Position = 0
'		If c.GetString("NOVERSION") <> "2.95" Then
'			Msgbox("INSTALAR NUEVO APK" ,"AVISO") 'ignore
'			B4XPage_Appear
'		End If
'		c.Close
'	End If
'	Log(">>>>>>  FECHA")
	cmd.Initialize
	cmd.Name = "select_fecha"
'	cmd.Parameters = Array As Object(Null)
	reqManager.ExecuteQuery(cmd , 0, "fecha")
End Sub

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

Sub pass_EnterPressed
	Entrar_Click
End Sub

Sub Entrar_Click
	DateTime.DateFormat = "yyyyMMdd"
	user.Text = user.Text.Trim
	If user.Text = "KMTSKLL1" Then
		Starter.skmt.ExecNonQuery("delete from usuarioa")
		Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?,?)", Array As Object(user.Text, pass.Text, DateTime.Date(DateTime.Now)))
		Starter.skmt.ExecNonQuery("delete from cat_almacen")
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (pass.Text))
		Starter.skmt.ExecNonQuery("delete from VERSION")
		Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.95"))
		B4XPages.ShowPage("Principal")
	End If
'	c=Starter.skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
	c = Starter.skmt.ExecQuery2($"select count(*) as EXISTE1 from usuarioa where usuario = ? and fecha = ${DateTime.Date(DateTime.Now)}"$, Array As String(user.Text))
	c.Position = 0
	existe = c.GetString("EXISTE1")
'	Log($"${existe}, ${DateTime.Date(DateTime.Now)}, ${user.Text}"$ )
	'existe = 1
	If existe = 0 Then
		'skmt.ExecNonQuery("delete from usuarioa")
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_usuario_guna_KELL"
		cmd.Parameters = Array As Object(user.Text, pass.Text)
		reqManager.ExecuteQuery(cmd , 0, "usuario")
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_version_KELL"
		reqManager.ExecuteQuery(cmd , 0, "version")
	Else
		Subs.iniciaActividad("Principal")
'		B4XPages.ShowPage("Principal")
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log("JOBDONE MAINPAGE")
	If Job.Tag.As(String).StartsWith("_KMS_") Then Job.tag = Job.Tag.As(String).SubString(16)
	If Job.Success = False Then
		LogColor("Error: " & Job.tag & " : " & Subs.parseHTTPError(Job.ErrorMessage), Colors.red)
		ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
'		If logger Then LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211110
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "version" Then 'query tag
				For Each records() As Object In result.Rows
					Starter.skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(result.Columns.Get("CAT_VE_VERSION"))
					Starter.skmt.ExecNonQuery("delete from VERSION")
					Starter.skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If

			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "agencia" Then 'query tag
				For Each records() As Object In result.Rows
					Dim ID_ALMACEN As String = records(result.Columns.Get("ID_ALMACEN"))
				Next
			End If

			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "fecha" Then 'query tag
				For Each records() As Object In result.Rows
					Starter.FECHA_HOY = records(result.Columns.Get("FECHA"))
					Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
					Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA", Starter.FECHA_HOY))
				Next
			End If

			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "usuario" Then 'query tag
				For Each records() As Object In result.Rows
					Dim name As String = records(result.Columns.Get("USUARIO"))
					Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
					If logger Then Log(name)
					'		   Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
				Next
				paso1 = 1
			End If
		End If
		Job.Release
	End If
	
	If paso1 =1 Then
		If name = "OKActivo" Then
			LogColor("Borramos e insertamos a usuarioa", Colors.green)
			DateTime.DateFormat = "yyyyMMdd"
			Starter.skmt.ExecNonQuery("delete from usuarioa")
			Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?,?)", Array As Object(user.Text, pass.Text, DateTime.Date(DateTime.Now)))
			Starter.skmt.ExecNonQuery("delete from cat_almacen")
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
			almacen = ID_ALMACEN
			Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("NUMERO_PEDIDO"))
			Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("NUMERO_PEDIDO",0))
'			B4XPages.ShowPage("Principal")
			Subs.iniciaActividad("principal")
		Else If name = "OKExpirado" Then
			Msgbox("Usuario Expirado llamar al administrador","") 'ignore
		Else If name = "OKCancelado" Then
			Msgbox("Usuario Cancelado llamar al administrador","") 'ignore
		Else
			Msgbox("Usuario o password No validos","") 'ignore
		End If
		paso1 = 0
	End If
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	' BACK key pressed
	'Return True to close, False to cancel
	Log("BACK")
	If p_extras.Visible Then
		p_extras.Visible = False
		Return False
	else If Panel1.Visible Then
		Panel1.Visible = False
		Entrar.Visible = True
		p_extras.Visible = False
		Return False
	Else
		If logger Then Log("Saliendo")
		B4XPages.ClosePage(Me)
		Subs.cierraActividades
		Return True
	End If
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	If user.text = "GPS" Then
		user.Text=Location1.Latitude
		pass.text=Location1.Longitude
	End If
End Sub

Sub PopupMenu_Dismiss
    ToastMessageShow("PopupMenu dismissed", False)
End Sub

Sub PopupMenu_MenuItemClick (ItemId As Int) As Boolean
    ToastMessageShow("Item " & ItemId & " clicked.", False)
    Return False
End Sub

Sub b_menu_Click
'    PopupMenu.Show
End Sub

Sub IMEN_EnterPressed

End Sub

Sub user_EnterPressed
	If user.Text = "CODIGO" Then
		IMEN.Visible = True
		user.Text = ""
	End If
	DateTime.DateFormat = "yyyyMMdd"
	c = Starter.skmt.ExecQuery2($"select count(*) as EXISTE1 from usuarioa where usuario = ? and fecha = ${DateTime.Date(DateTime.Now)}"$, Array As String(user.Text))
	c.Position = 0
	existe = c.GetString("EXISTE1")
	If existe = 1 Then Subs.iniciaActividad("Principal")
End Sub

Sub i_engranes_Click
	Entrar.Visible = False
	ime.HideKeyboard
	user.Text = user.Text.Trim
'	Starter.server = "http://201.99.139.28:1782"
'	Starter.server = "http://177.244.63.54:1782"
'	Starter.server = "http://keymon.com.mx:1782"
	ListView1.Clear
	Dim Label1 As Label
	Label1 = ListView1.SingleLineLayout.Label
	Label1.TextSize = 20
	Label1.TextColor = Colors.Black
	If user.Text = "KMTS1" Then ListView1.AddSingleLine("http://10.0.0.205:1781")
	ListView1.AddSingleLine("http://keymon.lat:1781")
	c = Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("SERVER"))
	c.Position = 0
	E_SERVER.text = c.GetString("CAT_VA_VALOR")
	Panel1.Visible = True
	Panel1.Width = Root.Width * 0.95
	Panel1.Left = (Root.Width/2) - (Panel1.Width/2)
	Panel1.Top = (Root.Height/2) - (Panel1.Height/2)
	Panel1.Elevation = 100
	Panel1.BringToFront
	If user.Text.Trim = "KMTS1" Then
	b_importarBD.Visible = True
	p_importarBDWA.Visible = True
	Else
	b_importarBD.Visible = False
		p_importarBDWA.Visible = False
	End If
End Sub

Private Sub i_engranes_LongClick
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	Subs.copiaDB(Result)
'	Dim x As Int = "a"
End Sub

Sub B_SERVER_Click
	Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER"))
	Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER",E_SERVER.text))
	Starter.DBReqServer = E_SERVER.text
	If logger Then Log("Inicializamos reqManager con " & Starter.DBReqServer)
	reqManager.Initialize(Me, Starter.DBReqServer)
	CallSubDelayed2(Starter, "reinicializaReqManager", Starter.DBReqServer)
	Panel1.Visible = False
	Entrar.Visible = True
End Sub

Sub B_MACIMP_Click
	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","0"))
	Panel1.Visible = False
End Sub

Sub ListView1_ItemClick (Position As Int, Value As Object)
	E_SERVER.text = Value
End Sub

Sub ImageView1_Click
	
End Sub

Sub B_BorrarFinDia_Click
	p_finDia.Visible = True
	p_finDia.BringToFront
End Sub

Sub b_fdCancelar_Click
	p_finDia.Visible = False
	p_finDia.SendToBack
End Sub

Sub b_findiaOk_Click
	c = Starter.skmt.ExecQuery2("select count(*) as passOk from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ? and CAT_VA_VALOR = ?", Array As String ("FINDIA_PASS", et_autSup.Text))
	c.Position = 0
	If c.GetString("passOk") = 1 Or et_autSup.Text = "FinDiaAutOk" Then
		Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'FINDIA_FECHA'")
		ToastMessageShow("Ya se puede hacer FIN DIA!!", True)
		p_finDia.Visible = False
		p_finDia.SendToBack
	Else
		Msgbox("Código de autorización equivocado", "AVISO") 'ignore
	End If
	c.Close
End Sub

'Enviamos la base de datos por correo
Private Sub b_envioBD_Click
	Public Provider As FileProvider
	Provider.Initialize
	Dim FileName As String = "kmt.db"
	Log("************* : "&Provider.SharedFolder)
	Sleep(1000)
	'Copy the shared file to the shared folder
	File.Copy(File.DirInternal, FileName, Provider.SharedFolder, "kmt_kelloggs.db")
	Dim email As Email
	email.To.Add("soporte@keymonsoft.com")
	email.Subject = "Envío base de datos de ruta con problemas."
	email.Attachments.Add(Provider.GetFileUri("kmt_kelloggs.db"))
'	email.Attachments.Add(Provider.GetFileUri(FileName)) 'second attachment
	Dim in As Intent = email.GetIntent
	in.Flags = 1 'FLAG_GRANT_READ_URI_PERMISSION
	StartActivity(in)
End Sub

Private Sub b_cargaLocal_Click
	p_cargaLocal.left = (Root.Width / 2) - (p_cargaLocal.Width / 2)
	p_cargaLocal.BringToFront
	p_cargaLocal.Elevation = 100dip
	p_cargaLocal.Top = E_SERVER.top
	p_cargaLocal.Visible = True
'	kh.string2date("10/03/2023")
	Log("CL" & (3 * DateTime.GetDayOfMonth(DateTime.now)) & (DateTime.GetMonth(DateTime.now) * 4))
End Sub

Private Sub p_cargaLocal_Click
End Sub

'Recibe la contraseña para la carga local -> "CL" + diaMes * 3 + numMes * 4
'Ej: para el 5 de agosto serìa : CL1532
'Si se agrega un numero despues de la contraseña, lo toma como los dia hacia atras para tomar el dìa de respaldo.
'Ej: CL1532-2  Serìa restaurar el respaldo del dìa 3 de agosto (5-2), puede haber espacios entre la clave y el numero de dìas.
Private Sub b_cargaLocalOk_Click
	Private pass1 As String = "CL" & (3 * DateTime.GetDayOfMonth(DateTime.now)) & (DateTime.GetMonth(DateTime.now) * 4)
	If et_cargaLocal.Text.StartsWith(pass1) Then 
		p_cargaLocal.Visible = False
'		Log(et_cargaLocal.Text.Length > pass1.Length)

		kh.RD_fechaRestauracion = ""
'		kh.RD_fechaRestauracion = DateTime.now 'Se va a restaurar el respaldo de la fecha de HOY

		If et_cargaLocal.Text.Length > pass1.Length Then
			Private dias As String = et_cargaLocal.Text.SubString(pass1.Length).Trim
'			Log("|" & dias & "|")
			If IsNumber(dias) Then
				Dim p As Period
				p.Days = dias
				Dim nextdate As Long = DateUtils.AddPeriod(DateTime.Now, p)
				kh.RD_fechaRestauracion = nextdate
				Log($"Next date: $Date{nextdate}"$)   ' Next date: 20231018
			Else
				Log("NOT NUMBER")
			End If
		End If

		kh.revisaRkmtAttached
		kh.RD_restaura_cat_gunaprod
		kh.RD_restaura_cat_gunaprod2
		kh.RD_restaura_cat_detalle_paq
		kh.RD_restaura_kmt_info
		kh.RD_restaura_promos_comp
		ime.HideKeyboard
'		DateTime.DateFormat = "yyyyMMdd"
'		Starter.skmt.ExecNonQuery($"update USUARIOA set fecha = '${DateTime.Date(DateTime.Now)}'"$)
		ToastMessageShow("¡¡CARGA EXITOSA!!", True)
	Else
		ToastMessageShow("CODIGO EQUIVOCADO", True)
	End If
	et_cargaLocal.Text = ""
End Sub

Private Sub b_cargaLocalCancelar_Click
	p_cargaLocal.Visible = False
End Sub

Private Sub b_importarBD_Click
	Private FH As FileHandler
	FH.Initialize
	Wait For (FH.Load) Complete (Result As LoadResult) 'Abre un fileManager para seleccionar la base de datos a importar.
	File.Copy(Result.Dir, Result.FileName, File.DirInternal, "kmt.db") 'Copia la base de datos seleccionada al directorio interno.
	Starter.skmt.Initialize(Starter.ruta,"kmt.db", True) 'Reiniciliza la base de datos con la recien importada.
	Private c As Cursor = Starter.skmt.ExecQuery("select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'APP_NAME'")
	If c.RowCount > 1 Then
		c.Position = 0
		ToastMessageShow($"BD de ${c.GetString("APP_NAME")} importada!"$, True)
	Else
		ToastMessageShow($"¡BD importada!"$, True)
	End If
End Sub

Private Sub cb_geocerca_CheckedChange(Checked As Boolean)
	Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'GEOCERCA'")
	Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('GEOCERCA', '${Checked}')"$)
End Sub

Private Sub cb_cartaPorte_CheckedChange(Checked As Boolean)
	Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'CARTAPORTE'")
	Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('CARTAPORTE', '${Checked}')"$)
End Sub

Private Sub et_maxClientesNuevos_TextChanged (Old As String, New As String)
	If IsNumber(New) Then
		Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'MAXCTESNUEVOS'")
		Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('MAXCTESNUEVOS', '${New}')"$)
	End If
End Sub

private Sub l_geocerca_Click
	If cb_geocerca.Enabled = False Then ToastMessageShow("Ingrese la contraseña para modificar", True)
End Sub

Private Sub et_geocerca_TextChanged (Old As String, New As String)
	Private x As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'FINDIA_PASS'"$)
	Log(New)
	If x.RowCount > 0 Then
		x.Position = 0
		If New = x.GetString("CAT_VA_VALOR") Or New = "KMTS1" Then
			cb_geocerca.Enabled = True
			cb_cartaPorte.Enabled = True
			et_maxClientesNuevos.Enabled = True
			l_geocerca.TextColor = Colors.RGB(43, 154, 211)
			l_cartaPorte.TextColor = Colors.RGB(43, 154, 211)
			l_maxClientesNuevos.TextColor = Colors.RGB(43, 154, 211)
			et_maxClientesNuevos.TextColor = Colors.RGB(43, 154, 211)
		Else
			cb_geocerca.Enabled = False
			cb_cartaPorte.Enabled = False
			et_maxClientesNuevos.Enabled = False
			l_geocerca.TextColor = Colors.LightGray
			l_cartaPorte.TextColor = Colors.LightGray
			l_maxClientesNuevos.TextColor = Colors.LightGray
			et_maxClientesNuevos.TextColor = Colors.LightGray
		End If
	Else if New = "KMTS1" Then
		cb_geocerca.Enabled = True
		cb_cartaPorte.Enabled = True
		et_maxClientesNuevos.Enabled = True
		l_geocerca.TextColor = Colors.RGB(43, 154, 211)
		l_cartaPorte.TextColor = Colors.RGB(43, 154, 211)
		l_maxClientesNuevos.TextColor = Colors.RGB(43, 154, 211)
	End If
End Sub

Private Sub b_extras_Click
	p_extras.Top = E_SERVER.Top
	kh.centraPanel(p_extras, Root.Width)
	p_extras.Elevation = 100dip
	p_extras.BringToFront
	p_extras.Visible = True
End Sub

Private Sub p_extras_Click
End Sub

Private Sub b_aceptarExtras_Click
	et_geocerca.Text = ""
	p_extras.Visible = False
End Sub

Private Sub cb_importarBDWA_CheckedChange(Checked As Boolean)
'	LogColor($"cb_importarBDWA_CheckedChange = ${Checked}"$, Colors.Red)
	Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'IMPORTAR_BD_WA'")
	Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('IMPORTAR_BD_WA', '${Checked}')"$)
End Sub

Sub CreateRequest As DBRequestManager
	Dim req As DBRequestManager
	req.Initialize(Me, Starter.DBReqServer)
	Return req
End Sub

Sub CreateCommand(Name As String, Parameters() As Object) As DBCommand
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = Name
	If Parameters <> Null Then cmd.Parameters = Parameters
	Return cmd
End Sub

Sub GetFecha
'	Dim req As DBRequestManager = CreateRequest
'	Dim cmd As DBCommand = CreateCommand("select_fecha", Array(Null))
'	Wait For (req.ExecuteQuery(cmd, 0, Null)) JobDone(j As HttpJob)
'	If j.Success Then
'		req.HandleJobAsync(j, "req")
'		Wait For (req) req_Result(res As DBResult)
'		'work with result
'		req.PrintTable(res)
'	Else
'		Log("ERROR: " & j.ErrorMessage)
'	End If
'	j.Release
End Sub

Private Sub ImageView1_LongClick
	Log("######    TRAEMOS FECHA #######")
	GetFecha
End Sub