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
'###########################################################################################################
'######################           PULL         #############################################################
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=..\..\gitpull.bat
'###########################################################################################################
'######################           PUSH         #############################################################
'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=github&Args=..\..\
'###########################################################################################################
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip
  
Sub Class_Globals
	Private Root As B4XView
	Private xui As XUI
	Public login As B4XMainPage
	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 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 ImageView4 As ImageView
	Private E_SERVER As EditText
	Private B_SERVER As Button
	Private B_FECHA 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
End Sub

Public Sub Initialize
	B4XPages.GetManager.LogEvents = True
	#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
	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.AddPage("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)
	ruta = Starter.ruta
	ruta = File.DirInternal
	Starter.tiempos.Initialize
	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 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  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  CLIENTE_CARGA_DIA (CCD_CUENTA 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
	
	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
	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.server))
	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.server))
	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("Revisa permisos para external storage")
	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.")
	Log("TERMINA PERMISOS")
	Log("Revisamos permisos para location")
	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
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_COARSE_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
	Log("TERMINA PERMISOS LOC")
	If logger Then LogColor("Revisa permisos Phone_State", Colors.Green)
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
'		Dim Phn As PhoneId
		IMEN.Text = ""
		IMEI = ""
		If logger Then LogColor($"//////////////////  IMEI: ${IMEI} ////////////////// "$, Colors.Blue)
	End If
	Log("TERMINA PERMISOS Phone")
	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"
			LogColor(File.DirInternal, Colors.Red)
		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)


	'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	
End Sub

Sub B4XPage_Appear
'	server = "http://keymon.com.mx:1782"
'	server = "http://201.99.139.28:1782"
'	server = "http://177.244.63.54:1782"
	reqManager.Initialize(Me, Starter.server)
	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
		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
End Sub

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

Sub Entrar_Click
	If user.Text = "ALTERNO" Then
		c=Starter.skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
		c.Position =0
		Starter.server = c.GetString("CAT_CO_CONFIGURACION")
		alterno = c.GetString("CAT_CO_RESULTADO")
		c.Close
		If alterno = 1 Then
			Starter.skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
			Starter.skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
		Else if alterno = 2 Then
			Starter.skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
			Starter.skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
		End If
		c=Starter.skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
		c.Position =0
		Starter.server = c.GetString("CAT_CO_CONFIGURACION")
		user.Text = Starter.server
		c.Close
		reqManager.Initialize(Me, Starter.server)
	else 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))
		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.Position=0
	existe = c.GetString("EXISTE1")
	'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
		B4XPages.ShowPage("Principal")
	End If
End Sub

Sub JobDone(Job As HttpJob)
	If Job.Success = False Then
		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
		End If

		If Job.JobName = "DBRequest" Then
			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
		End If

		If Job.JobName = "DBRequest" Then
			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
		End If

		If Job.JobName = "DBRequest" Then
			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
			Starter.skmt.ExecNonQuery("delete from usuarioa")
			Starter.skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
			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")
		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 Panel1.Visible Then
		Panel1.Visible = False
		Entrar.Visible = True
		Return True
	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
End Sub

Sub ImageView4_Click
	Entrar.Visible = False
'	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:1782")
	ListView1.AddSingleLine("http://keymon.lat:1782")
	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
End Sub

Private Sub ImageView4_LongClick
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
	Subs.copiaDB(True)
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.server = E_SERVER.text
	If logger Then Log("Inicializamos reqManager con " & Starter.server)
	reqManager.Initialize(Me, Starter.server)
	CallSubDelayed(Starter, "reinicializaReqManager")
	Panel1.Visible = False
	Entrar.Visible = True
End Sub

Sub B_FECHA_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