//localStorage.clear();

window.COM_TIMEFORMAT = 'YYYY-MM-DD HH:mm:ss';
window.COM_TIMEFORMAT2 = 'YYYY-MM-DDTHH:mm:ss';
window.COM_TIMEFORMAT3 = 'DD/MM/YYYY HH:mm:ss';
window.COM_TIMEFORMAT4 = 'DD/MM/YYYY';
window.COM_TIMEFORMAT5 = 'MMM DD YYYY, HH:mm';

var API_DOMIAN0 = "https://newapi.quiktrak.co/";
var API_DOMIAN1 = "https://newapi.quiktrak.co/QuikProtect/V1/Client/";
var API_DOMIAN2 = "https://newapi.quiktrak.co/QuikTrak/V1/";
var API_DOMIAN2__ = "https://testapi.quiktrak.co/QuikTrak/V1/";
var API_DOMIAN3 = "https://quiktrak.co/webapp/QuikProtect/Api2/";
var API_DOMIAN4 = "https://newapi.quiktrak.co/Quikloc8/V1/";
var API_DOMIAN4_ = "https://api.m2mglobaltech.com/Quikloc8/V1/";
var API_DOMIAN4__ = "https://testapi.quiktrak.co/Quikloc8/V1/";
var API_DOMIAN5 = "https://newapi.quiktrak.co/Common/V1/Activation/";
var API_DOMIAN6 = "https://nomad.sinopacific.com.ua/";
var API_DOMIAN7 = "https://ss.sinopacific.com.ua/";
var API_DOMIAN8 = "https://newapi.quiktrak.co/";
var API_DOMIAN10 = "https://m2mdata03.sinopacific.com.ua/";
var API_DOMIAN11 = "https://pdf.m2mdata.co/";
var API_DOMIAN12 = "https://newapi.quiktrak.co/Installer/V1/Client/";
var API_DOMIAN13 = "https://newapi.quiktrak.co/QuikTrak/V2/";
var API_DOMIAN14 = "https://newapi.quiktrak.co/QuikTrak/V1/";
var API_DOMIAN15 = "https://newapi.quiktrak.co/QuikData/V1/";
var API_DOMIAN16 = "https://testapi.quiktrak.co/" 
//https://m2mdata03.sinopacific.com.ua/api/v2/reports/Playback

//https://nomad.sinopacific.com.ua/reports/5db9a8544407c912842b2a6a.pdf?MajorToken=f9087bb0-47ba-4d31-a038-ea676fdf0de2&MinorToken=8471d88c-4394-4e23-945d-2b514c382bd1&DateFrom=2019-10-10%2009%3A16%3A58&DateTo=2019-10-10%2010%3A16%3A58&Imeis%5B%5D=0000004209084060&Imeis%5B%5D=0863014530509904&Imeis%5B%5D=0352544074319915&Imeis%5B%5D=0352544073223399&Imeis%5B%5D=0000142170222884&Recipients%5B%5D=bitman%40sinopacificukraine.com
var API_URL = {};

var USERROLE = 0;
var PERMISSIONS = 0;

API_URL.HANDLE_USER = API_DOMIAN8 + 'QuikTrak/V2/User/Handle'

API_URL.GET_ASSET_LIST = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/GETLIST';

//API_URL.LOGIN = API_DOMIAN4 + "user/Auth2";
API_URL.LOGIN = API_DOMIAN4__ + "user/Auth2";

//API_URL.LOGIN = API_DOMIAN4__ + "user/AUTHNEW";
API_URL.LOGOUT = API_DOMIAN1 + "Logoff";
API_URL.GET_ALL_POSITIONS = API_DOMIAN2 + "Device/GetPosInfosDB";
API_URL.EDIT_DEVICE = API_DOMIAN2 + "Device/Edit";
API_URL.SET_ALARM = API_DOMIAN4 + "asset/AlarmOptions";

API_URL.SET_ALARM_LOC8 = API_DOMIAN4 + "asset/AlarmOptions";
API_URL.SET_ALARM_PROTECT = API_DOMIAN1 + "AlarmOptions2";
API_URL.GET_ALERT_CONFIG = API_DOMIAN2 + "Device/GetAlertConfigure1";
API_URL.SET_ALERT_CONFIG = API_DOMIAN2 + "Device/AlertConfigureEdit1";

API_URL.GET_BALANCE = API_DOMIAN1 + "Balance";
API_URL.PHOTO_UPLOAD = "https://upload.quiktrak.co/image/Upload";
API_URL.EDIT_ACCOUNT = API_DOMIAN1 + "AccountEdit";
API_URL.RESET_PASSWORD = API_DOMIAN2 + "User/Password";
API_URL.SUPPORT = "https://support.cartrack.co/";
API_URL.PREUPGRADE = API_DOMIAN4 + "asset/PreUpgrade";
API_URL.GET_NEW_NOTIFICATIONS = API_DOMIAN4 + "asset/Alarms";
API_URL.SET_GEOLOCK = API_DOMIAN4 + "asset/GeoLock";
API_URL.SET_IMMOBILISATION = API_DOMIAN4 + "asset/Relay";
API_URL.SET_DOORLOCK = API_DOMIAN4 + "asset/door";
API_URL.GET_ACTIVATION_SSP = API_DOMIAN5 + "SSP";
API_URL.GET_ACTIVATION_VERIFY = API_DOMIAN5 + "Verify";
API_URL.ASSET_DEACTIVATE = API_DOMIAN5 + "DeActivate";
API_URL.ACTIVATION = 'https://app.quikprotect.co/activation2/';
API_URL.SEND_COM_POS = API_DOMIAN1 + "Location";
API_URL.SEND_COM_STATUS = API_DOMIAN1 + "Status";

API_URL.URL_SEND_SMS_BY_TYPE = API_DOMIAN15 + "Command/SendByType";
API_URL.URL_SEND_SMS_BY_TYPE_VIA_TCP = API_DOMIAN15 + "Command/SendByTypeViaTcp";


API_URL.GET_GEOFENCE_LIST = API_DOMIAN2 + "Device/GetFenceList";
API_URL.GEOFENCE_ADD = API_DOMIAN2 + "Device/FenceAdd";
API_URL.GEOFENCE_EDIT = API_DOMIAN2 + "Device/FenceEdit";
API_URL.GEOFENCE_DELETE = API_DOMIAN2 + "Device/FenceDelete";

API_URL.GET_GROUP_LIST = API_DOMIAN4 + "GeoGroup/GetList";
API_URL.EDIT_GROUP = API_DOMIAN4 + "GeoGroup/Edit";
API_URL.REMOVE_GROUP = API_DOMIAN4 + "GeoGroup/Remove";

API_URL.GET_PLAYBACK_ARR = API_DOMIAN2__ + "Device/GetHisPosArray2";
API_URL.GET_PLAYBACK_ARR_OPTIMISED = "https://osrm.sinopacific.com.ua";
API_URL.GET_PLAYBACK_ARR_OPTIMISED2 = "https://osrm.sinopacific.com.ua/playback/v2";
API_URL.GET_ADDRESSES_FROM_ARRAY = API_DOMIAN7 + "geocode/reverse/v1";
API_URL.GET_SPEEDLIMIT = API_DOMIAN7 + "speedlimits/v1";

API_URL.GET_USERS_LIST = API_DOMIAN4_ + "SubDealer/GetList";
//API_URL.GET_USERS_LIST = API_DOMIAN2 + "User/GetList";
API_URL.USER_ADD = API_DOMIAN4_ + "SubDealer/Add";
API_URL.USER_EDIT = API_DOMIAN4_ + "SubDealer/Edit";
API_URL.USER_DELETE = API_DOMIAN4_ + "SubDealer/Delete";
API_URL.USER_RESET_PASSWORD = API_DOMIAN4_ + "SubDealer/ResetPassword";

API_URL.GET_CUSTOMER_LIST = API_DOMIAN13 + "Customer/GetList";

API_URL.GET_CONTACT_USERS_LISTNEW = API_DOMIAN2 + "User/GetList";
API_URL.GET_CONTACT_USERS_LIST = API_DOMIAN2__ + "User/GetList";
API_URL.CONTACT_USER_ADD = API_DOMIAN2 + "User/Add";
API_URL.CONTACT_USER_EDIT = API_DOMIAN2 + "User/Edit";
API_URL.CONTACT_USER_ADDNEW = API_DOMIAN2 + "User/AddNew";
API_URL.CONTACT_USER_EDITNEW = API_DOMIAN2 + "User/EditNew";
API_URL.CONTACT_USER_DELETE = API_DOMIAN2 + "User/DeleteNew";

API_URL.GET_DASHBOARD_DATA = API_DOMIAN4__ + "User/Dashboard";
API_URL.GET_DASHBOARD_OVERVIEW_INFO = API_DOMIAN2 + "Report/GetOverviewEx";
API_URL.GET_DASHBOARD_ENDUSER_OVERVIEW = API_DOMIAN4 + "User/OverViewReport";
API_URL.GET_DASHBOARD_ENDUSER_ALARM_LOG = API_DOMIAN4 + "User/AlarmLogReport";
API_URL.GET_DASHBOARD_ENDUSER_DEVICE_STATUS = API_DOMIAN4 + "User/DeviceStatusReport";

//fAPI_URL.GET_REPORT_BY_ALERT = API_DOMIAN2 + "Report/GetAlertReportData";
API_URL.GET_REPORT_BY_ALERT = API_DOMIAN2__ + "Report/GetAlertReportData";
API_URL.GET_REPORT_ALERTLIST = API_DOMIAN2 + "Report/GetAlertList";
API_URL.GET_REPORT_BY_NOTREPORTING = API_DOMIAN2 + "Report/GetNotReporting";
API_URL.GET_REPORT_BY_DEVICESOLD = API_DOMIAN2 + "Report/GetDevicesSold";
API_URL.GET_REPORT_BY_DEVICESOLD2 = API_DOMIAN2 + "Report/GetDevicesSold2";
API_URL.GET_REPORT_BY_GEOGROUP = API_DOMIAN2 + "Report/GetAssetListByGeogroup";
API_URL.GET_REPORT_BY_DRIVEOFF = API_DOMIAN2 + "Report/GetDriveOff2";
API_URL.GET_REPORT_BY_GEOGROUP_COUNT = API_DOMIAN2 + "Report/GetGeogroupLotAssetCount";
API_URL.GET_REPORT_BY_GEOFENCE_COUNT = API_DOMIAN2 + "Report/GetGeofenceLotAssetCount";
API_URL.GET_REPORT_TRIP = API_DOMIAN2 + "Report/GetTripReport";
API_URL.GET_REPORT_TRIP2 = API_DOMIAN2 + "Report/GetTripReport2";
API_URL.GET_REPORT_LOW_BATTERY = API_DOMIAN2 + "Report/GetLowBattery";
API_URL.GET_REPORT_SERVICING_OVERVIEW = API_DOMIAN2 + "Report/GetServiceIntervalOverview";
API_URL.GET_REPORT_OVERVIEW = API_DOMIAN2 + "Report/GetOverview";
API_URL.GET_REPORT_EVENT = API_DOMIAN2 + "Report/GetEventReport";
API_URL.GET_REPORT_BY_GEOFENCE = API_DOMIAN2 + "Report/GetGeofenceReport";
API_URL.GET_REPORT_LOT_OVERVIEW = API_DOMIAN2 + "Report/GetIotOverviewReport";
API_URL.GET_REPORT_FLEET = API_DOMIAN2 + "Report/GetOverViewReport";
API_URL.GET_REPORT_ACTIVATIONS = API_DOMIAN2 + "Report/GetActivationLog";
API_URL.GET_REPORT_DRIVER_BEHAVIOUR = API_DOMIAN2 + "Device/DriverBehaviour2";
API_URL.GET_REPORT_DRIVER_ID = API_DOMIAN8 + "Quiktrak/V2/Report/DriverDetails";
//https://newapi.quiktrak.co/quiktrak/v1/device/DriverBehaviour2

API_URL.GET_WEBSITES = API_DOMIAN0 + 'QuikTrak/V1/Device/GetWebsitesOfAgent';


//API_URL.GET_FTC_REPORT_ON_MAIL = API_DOMIAN6 + "reports/5db9a8544407c912842b2a6a.pdf";
API_URL.GET_FTC_REPORT_ON_MAIL = API_DOMIAN10 + "api/v2/reports/FuelTaxCredit";
API_URL.GET_PLAYBACK_REPORT_ON_MAIL = API_DOMIAN10 + "api/v2/reports/Playback";

API_URL.GET_SCHEDULE_REPORT_LIST = API_DOMIAN2 + "Device/GetScheduleList";
API_URL.SET_SCHEDULE_REPORT = API_DOMIAN2 + "Device/SetSchedule";
API_URL.SCHEDULED_REPORT_DELETE = API_DOMIAN2 + "Device/RemoveSchedule";


API_URL.GET_SERVICE_INTERVALS_LIST = API_DOMIAN4 + "ServiceInterval/GetList";
API_URL.SERVICE_INTERVAL_REMOVE = API_DOMIAN4 + "ServiceInterval/Delete";
API_URL.SERVICE_INTERVAL_ADD = API_DOMIAN4 + "ServiceInterval/Add";
API_URL.SERVICE_INTERVAL_EDIT = API_DOMIAN4 + "ServiceInterval/Edit";
API_URL.GET_SERVICE_INTERVAL_MODEL = API_DOMIAN4 + "ServiceInterval/GetModel";
API_URL.GET_SERVICE_INTERVAL_PARAMS = API_DOMIAN4 + "ServiceInterval/GetParameters";

API_URL.GET_ASSET_RAITING = API_DOMIAN2 + "Device/DriverBehaviour";
API_URL.SET_USER_ALARMSETTINGS = API_DOMIAN2 + "User/AlarmSettings";
API_URL.GET_OBD_INFO = API_DOMIAN2 + "Device/OBDINFO";

API_URL.REPORT_PLAYBACK_GENERATE = API_DOMIAN11 + "pdf/Generate";
API_URL.REPORT_PLAYBACK_QUERY_STATE = API_DOMIAN11 + "pdf/QueryState";
API_URL.REPORT_PLAYBACK_DOWNLOAD = API_DOMIAN11 + "pdf/download";
API_URL.REPORT_PLAYBACK_SEND_EMAIL = API_DOMIAN2 + "device/SendPlayBackReport";
API_URL.REPORT_PLAYBACK_URL_TEMPLATE = "https://helpers.quiktrak.eu/pdf/playback/";

API_URL.GET_ASSET_LAST_ALARMS = API_DOMIAN12 + "GetTop5Alarms";
API_URL.CCTV_SRC = "https://securetrack.co/808gps/open/player/1.html";
API_URL.CCTV_SRC2 = "https://securetrack.co/808gps/open/player/video.html";

API_URL.GET_MY_SHARED_ASSET_LIST = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/QuerySharedInfos';
API_URL.GET_SUBSCRIBED_ASSET_LIST = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/QueryShareRelations';
API_URL.START_SHARE_ASSET = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/StartShare';
API_URL.STOP_SHARE_ASSET = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/CloseShare';
API_URL.SUBSCRIBE_TO_ASSET_SHARE_CODE = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/BindShareRelation';
API_URL.UNSUBSCRIBE_FROM_ASSET_SHARE_CODE = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/UnboundShareRelation';
API_URL.EDIT_ASSET_SHARE_CODE = API_DOMIAN8 + 'QUIKTRAK/V2/ASSET/EditShare';

API_URL.SET_RULES = API_DOMIAN14 + 'Device/SetDriverFatigueRules'
API_URL.GET_RULES = API_DOMIAN14 + 'Device/GetDriverFatigueRules'
API_URL.SET_RULES_TRIPBAN = API_DOMIAN13 + 'TripBan/Edit'
//TripBan/Edit?MajorToken=f9087bb0-47ba-4d31-a038-ea676fdf0de2&Assets=0000142170222884,0352544074319915&TimeFrom=18:00&TimeTo=21:00&Days=6,7&IsAutoImmobilize=true&IsImmobilize=true
API_URL.GET_RULES_TRIPBAN = API_DOMIAN13 + 'TripBan/GetListbyCustomer'
//TripBan/GetListbyCustomer?MajorToken=f9087bb0-47ba-4d31-a038-ea676fdf0de2


API_URL.PRE_EDIT_CUSTOMER = API_DOMIAN13 + "Customer/PreEdit";
API_URL.RESET_MILEAGE = API_DOMIAN0 + 'Quiktrak/V2/Asset/ResetMileage'
API_URL.RESET_HISTORY = API_DOMIAN0 + 'Quiktrak/V2/Asset/ClearHistory'
API_URL.RESET_HOURS = API_DOMIAN0 + 'Quiktrak/V2/Asset/ResetLaunchHours'

API_URL.GET_POI_LIST = API_DOMIAN14 + "Device/GetPOIList";


API_URL.GET_TASK_OF_DRIVER = API_DOMIAN0 +'prestart/v1/user/GetAllTaskOfDriver';
API_URL.GET_TRIP_OF_DRIVER = API_DOMIAN0 +'/prestart/v1/user/QueryTrip';
API_URL.GET_CHECKLIST = API_DOMIAN0 +'/prestart/v1/user/GetCheckList'; 
 
API_URL.GET_TRIP_EXTENDED_REPORT = API_DOMIAN0 + 'PreStart/V1/User/TripReport'
 
API_URL.SET_IBUTTONS = API_DOMIAN14 + '/Device/SetIButtonsNew'
API_URL.GET_IBUTTONS = API_DOMIAN14 + '/Device/GetIButtons'


API_URL.GET_ALERTPHOTO_LIST = API_DOMIAN2 + "device/GetPhotoLogs";
API_URL.REMOVE_ALERTPHOTO = API_DOMIAN2 + "device/DeletePhotoLogs";
API_URL.GET_LIVE_SESSION = API_DOMIAN2 + "USER/GetStramToken";

API_URL.GET_TEMPLATES_LIST = API_DOMIAN16 + "DriverJob/V1/Jobs/GetTemplates";  
API_URL.ADD_TEMPLATE = API_DOMIAN16 + "DriverJob/V1/Jobs/AddTemplate"; 
API_URL.JOB_TEMPLATE_EDIT = API_DOMIAN0 + 'DriverJob/V1/Jobs/EditTemplate'
API_URL.JOB_TEMPLATE_DELETE = API_DOMIAN0 + 'DriverJob/V1/Jobs/DeleteTemplate'
API_URL.NEW_TASK = API_DOMIAN0 + 'DriverJob/V1/Jobs/NewTask'
API_URL.GET_TASKS = API_DOMIAN0 + 'DriverJob/V1/Jobs/GetTasks'
API_URL.NEW_ORDER = API_DOMIAN0 +'DriverJob/V1/Jobs/NewOrder'
API_URL.EDIT_ORDER = API_DOMIAN0 +'DriverJob/V1/Jobs/EditOrder'
API_URL.DELETE_ORDER = API_DOMIAN0 +'DriverJob/V1/Jobs/DeleteOrder'
API_URL.TASK_DELETE = API_DOMIAN0 + "DriverJob/V1/Jobs/DeleteTask"
API_URL.JOB_TASK_UPDATE =  API_DOMIAN0 + "DriverJob/V1/Jobs/EditTask"




 //https://newapi.quiktrak.co/Installer/V1/Client/GetTop5Alarms?asId=47861
//quiktrak/device/SetSchedule
//quiktrak/device/GetScheduleList

//https://newapi.quiktrak.co/Quiktrak/V1/Report/GetOverviewEx
//quiktrak/v1/report/overview
//https://newapi.quiktrak.co/QuikTrak/V1/Report/GetServiceIntervalOverview

//API_URL.URL_GET_ASSET_DETAILS = API_DOMIAN4 + "asset/GetModel?MinorToken={0}&code={1}";
//API_URL.URL_ROUTE = "https://www.google.com/maps/dir/?api=1&destination={0},{1}";




var POSINFOASSETLIST = {};
var MapTrack;
//var MapDashboard;
var AllMarkersGroup = false;
//var AllMarkersGroupDashboard = false;
var UpdateAssetsPosInfoTimer = false;
var UpdateNotificationsTimer = false;
var AutoUpdateDashboardDataTimer = false;
var GroupRadius = false;
var GroupMarkers = false;
//var DashboardCharts = {};
var DATATABLEReport = false;

var GeoSearchControl = window.GeoSearch.GeoSearchControl;
var OpenStreetMapProvider = window.GeoSearch.OpenStreetMapProvider;
var MapProvider = new OpenStreetMapProvider();

// Dom7
var $$ = Dom7;

var parsedUrl = psl.parse(window.location.hostname);
let parsedPath = window.location.pathname.split('/')[1]
let parsedDealer = window.location.pathname.split('/')[2]


var dealerData = {
	portalName: 'QuikLoc8 Portal',
	name: 'QuikLoc8-Portal',
	code: 39,
	supportCode: 39,
	supportPageUrl: API_URL.SUPPORT,
	logoSrc: '../resources/images/logo.svg',                           //logo on login page
	logoLetterSrc: '../resources/images/mail-templates/logo.png',      //logo on user creation letter, and in exported report in PNG forma
	logoModal: '../resources/images/logo-modal.svg',                   //logo on portal modals
	logoExternal: 'https://client.quikloc8.com/resources/images/login/client/logo.png',  //logo for email reports
	//logoExternal: 'https://wardengps.com/resources/images/login/warden/logoWarden.png',
	loginScreenBgClass: '',
	loginScreenCustom: '',
	favicon: '../resources/images/favicon.png',
	loginUrl: window.location.origin + '/', // window.location.href,
	agentLoginUrl: 'https://quiktrak.co/',
	customMapMarker: '',
	isMarine: false,
	activationAutosuspend: false,
	manuals: {
		dealer: [
			{
				name: LANGUAGE.HOME_MSG028,
				url: '../resources/manuals/dealer/user-guide.pdf',
			},
			{
				name: LANGUAGE.HOME_MSG029,
				url: '../resources/manuals/dealer/user-guide-es.pdf',
			},
			{
				name: LANGUAGE.HOME_MSG030,
				url: '../resources/manuals/dealer/dealer-installer-app-guide.pdf',
			},
			{
				name: LANGUAGE.HOME_MSG031,
				url: '../resources/manuals/dealer/dealer-installer-app-guide-es.pdf',
			}
		],
		enduser: [
			{
				name: LANGUAGE.HOME_MSG028,
				url: '../resources/manuals/enduser/user-guide.pdf',
			},
			{
				name: LANGUAGE.HOME_MSG029,
				url: '../resources/manuals/enduser/user-guide-es.pdf',
			}
		]
	}
};
Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-dealer';
Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-dealer';
Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'red';

//console.log(parsedDealer, 'parsedDealer')

//if (parsedUrl.sld === 'wardengps') {
if (parsedDealer === 'wardengps') {
	dealerData = {
		portalName: 'WardenGPS Portal',
		name: 'WardenGPS-Portal',
		code: 29,
		supportCode: 29,
		supportPageUrl: 'https://support.wardengps.com/',
		logoSrc: '../resources/images/login/warden/logoWarden.png',
		logoLetterSrc: '../resources/images/login/warden/logoWarden.png',
		logoModal: '../resources/images/login/warden/logoWarden.png',
		logoExternal: 'https://wardengps.com/resources/images/login/warden/logoWarden.png',
		favicon: '../resources/images/login/warden/faviconWarden.png',
		loginScreenBgClass: 'login-screen-content-warden',
		loginUrl: window.location.origin + '/', //window.location.href,
		loginScreenCustom: true,
		agentLoginUrl: 'https://warden.quiktrak.eu/',
		/*additionalLoginLogos:[
				'../resources/images/login/warden/route-66-chevrolet-logo.png',
				'../resources/images/login/warden/route-66-nissan-logo.png',
			],*/
		videoDemo: 'https://youtu.be/Xuu5MVtYCrg',
		brochure: '../resources/manuals/warden/brochure/4G-QT-LTE-500.pdf',
		activationAutosuspend: true,
		manuals: {
			dealer: [
				{
					name: LANGUAGE.HOME_MSG028,
					url: '../resources/manuals/warden/dealer/user-guide.pdf',
				},
				{
					name: LANGUAGE.HOME_MSG029,
					url: '../resources/manuals/warden/dealer/user-guide-es.pdf',
				},
				{
					name: LANGUAGE.HOME_MSG030,
					url: '../resources/manuals/dealer/dealer-installer-app-guide.pdf',
				},
				{
					name: LANGUAGE.HOME_MSG031,
					url: '../resources/manuals/dealer/dealer-installer-app-guide-es.pdf',
				}
			],
			enduser: [
				{
					name: LANGUAGE.HOME_MSG028,
					url: '../resources/manuals/warden/enduser/user-guide.pdf',
				},
				{
					name: LANGUAGE.HOME_MSG029,
					url: '../resources/manuals/warden/enduser/user-guide-es.pdf',
				}
			]
		}
	};
	dealerData.customMapMarker = L.icon({
		iconUrl: '../resources/images/marker-wardengps.svg',
		iconSize: [40, 40], // size of the icon
		iconAnchor: [20, 39], // point of the icon which will correspond to marker's location
		popupAnchor: [0, -40] // point from which the popup should open relative to the iconAnchor
	});
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	$$("body").addClass('theme-wardengps');
	API_URL.ACTIVATION = 'https://activation.warden.quiktrak.eu/';
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-wardengps';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-wardengps';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'blue';

	//if (parsedDealer === 'wardengps') {

} else if (parsedDealer === 'quiktrak') {
	
	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "client") {
	dealerData.portalName = 'QuikTrak Portal';
	dealerData.name = 'QuikTrak-Portal';
	dealerData.code = 32;
	dealerData.supportCode = 32;

	dealerData.supportPageUrl = 'https://support.quiktrak.au/?s=32';
	dealerData.logoSrc = '../resources/images/login/client/logo.svg';
	dealerData.logoLetterSrc = '../resources/images/login/client/logo.png';
	dealerData.logoModal = '../resources/images/login/client/logo.svg';
	dealerData.favicon = '../resources/images/login/client/fav.png';
	dealerData.loginScreenBgClass = 'login-screen-content-client';
	dealerData.loginScreenCustom = true;

	dealerData.loginUrl = window.location.origin + '/'; //window.location.href;

	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);

	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "test") {
} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "test") {
	dealerData.portalName = 'QuikTrak Portal';
	dealerData.name = 'QuikTrak-Portal';
	dealerData.code = 40;
	dealerData.supportCode = 40;
	dealerData.supportPageUrl = API_URL.SUPPORT;
	dealerData.logoSrc = '../resources/images/login/client/logo.svg';
	dealerData.logoLetterSrc = '../resources/images/login/client/logo.png';
	dealerData.logoModal = '../resources/images/login/client/logo.svg';
	dealerData.favicon = '../resources/images/login/client/fav.png';

	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);

	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "classic") {
} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "classic") {
	dealerData.portalName = 'ClassicCheriots Portal';
	dealerData.name = 'ClassicCheriots-Portal';
	dealerData.code = 40;
	dealerData.supportCode = 40;
	dealerData.supportPageUrl = API_URL.SUPPORT;
	dealerData.logoSrc = '../resources/images/login/classic/logo.png';
	dealerData.logoLetterSrc = 'https://classic.quikloc8.com/img/logo-cc.png';
	dealerData.logoModal = '../resources/images/login/classic/logo.png';
	dealerData.logoExternal = 'https://classic.quikloc8.com/app/resources/images/login/classic/logo.png';
	dealerData.favicon = '../resources/images/login/classic/fav.png';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://classic.quikloc8.com/manuals/CC-portal-client-compress.pdf',
		}];


	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'green';

	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "carcitywest") {
} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "carcitywest") {
	dealerData.portalName = 'Car City West Portal';
	dealerData.name = 'CarCityWest-Portal';
	dealerData.code = 40;
	dealerData.supportCode = 40;
	dealerData.supportPageUrl = 'https://support.carcitywest.quiktrak.eu/';
	dealerData.logoSrc = 'https://carcitywest.quikloc8.com/img/logo.png';
	dealerData.logoLetterSrc = 'https://carcitywest.quikloc8.com/img/logo.png';
	dealerData.logoModal = 'https://carcitywest.quikloc8.com/img/logo.png';
	dealerData.logoExternal = 'https://carcitywest.quikloc8.com/img/logo.png';
	dealerData.favicon = 'https://carcitywest.quikloc8.com/img/fav.png';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://carcitywest.quikloc8.com/manuals/ccw-portal-client.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://carcitywest.quikloc8.com/manuals/ccw-portal-dealer.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);

} else if (parsedDealer === 'selftrack') {
	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "selftrack" || parsedUrl.sld === "selftrack") {
	dealerData.portalName = 'SelfTrack';
	dealerData.name = 'SelfTrack-Portal';
	dealerData.code = 23;
	dealerData.supportCode = 23;
	dealerData.supportPageUrl = 'https://support.selftrack.co/?s=23';

	dealerData.logoSrc = '../resources/images/login/selftrack/logo.svg';
	dealerData.logoLetterSrc = '../resources/images/login/selftrack/logo.png';
	dealerData.logoModal = '../resources/images/login/selftrack/logo.svg';
	dealerData.favicon = '../resources/images/login/selftrack/fav.png';
	dealerData.loginScreenBgClass = 'login-screen-content-selftrack';
	dealerData.loginScreenCustom = true; //

	dealerData.loginUrl = window.location.origin + '/'; //window.location.href; 

	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);

	API_URL.ACTIVATION = 'https://activation.selftrack.co/';

} else if (parsedDealer === 'boatwatch') {
	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "marine") {
	dealerData.portalName = 'BoatWatch';
	dealerData.name = 'Boatwatch-Portal';
	dealerData.isMarine = true;

	dealerData.code = 22;
	dealerData.supportCode = 22;
	dealerData.logoSrc = 'https://marine.quikloc8.com/img/logo.png';
	dealerData.logoLetterSrc = 'https://marine.quikloc8.com/img/logo.png';
	dealerData.logoModal = 'https://marine.quikloc8.com/img/logo.png';
	dealerData.logoExternal = 'https://marine.quikloc8.com/img/logo.png';
	dealerData.favicon = 'https://marine.quikloc8.com/img/fav.png';
	/*dealerData.manuals.enduser = [
		  {
			  name: LANGUAGE.HOME_MSG028,
			  url: 'https://carcitywest.quikloc8.com/manuals/ccw-portal-client.pdf',
		  }];
	  dealerData.manuals.dealer =[
		  {
			  name: LANGUAGE.HOME_MSG028,
			  url: 'https://carcitywest.quikloc8.com/manuals/ccw-portal-dealer.pdf',
		  }];*/
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);

	dealerData.customMapMarker = L.icon({
		iconUrl: '../resources/images/marker-marine.svg',
		iconSize: [40, 40], // size of the icon
		iconAnchor: [20, 39], // point of the icon which will correspond to marker's location
		popupAnchor: [0, -40] // point from which the popup should open relative to the iconAnchor
	});

	$$("body").addClass('theme-marine');
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-marine';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-marine';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'marine';
} else if (parsedDealer === 'geelinx') {
	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "geelinxgps" || parsedUrl.sld === "geelinxgps") {
	//console.log('here')
	dealerData.portalName = 'GeelinxGPS';
	dealerData.name = 'GeelinxGPS-Portal';
	dealerData.code = 13;
	dealerData.supportCode = 13;
	dealerData.supportPageUrl = 'https://support.geelinxgps.quiktrak.eu/';
	dealerData.logoSrc = 'https://geelinxgps.quikloc8.com/img/logo.png';
	dealerData.logoLetterSrc = 'https://geelinxgps.quikloc8.com/img/logo.png';
	dealerData.logoModal = 'https://geelinxgps.quikloc8.com/img/logo.png';
	dealerData.logoExternal = 'https://geelinxgps.quikloc8.com/img/logo.png';
	dealerData.favicon = 'https://geelinxgps.quikloc8.com/img/fav.png';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://geelinxgps.quikloc8.com/manuals/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://geelinxgps.quikloc8.com/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-geelinxgps';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-geelinxgps';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'geelinxgps';

	API_URL.ACTIVATION = 'https://activation.geelinxgps.quiktrak.eu/';
} else if (parsedUrl.subdomain === "cube") {
	//} else if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "cubetrackit" || parsedUrl.sld === "cubetrackit") {
	//console.log('here')
	dealerData.portalName = 'CubeTrackIT';
	dealerData.name = 'CubeTrackIT-Portal';
	dealerData.code = 10;
	dealerData.supportCode = 10;
	dealerData.supportPageUrl = 'https://support.cubetrackit.quiktrak.eu/';
	dealerData.logoSrc = 'https://cubetrackit.quikloc8.com/img/logo.png';
	dealerData.logoLetterSrc = 'https://cubetrackit.quikloc8.com/img/logo.png';
	dealerData.logoModal = 'https://cubetrackit.quikloc8.com/img/logo.png';
	dealerData.logoExternal = 'https://cubetrackit.quikloc8.com/img/logo.png';
	dealerData.favicon = 'https://cubetrackit.quikloc8.com/img/fav.png';
	dealerData.agentLoginUrl = 'https://cube.quiktrak.co/',
		dealerData.manuals.enduser = [
			{
				name: LANGUAGE.HOME_MSG028,
				url: 'https://cubetrackit.quikloc8.com/manuals/user-guide.pdf',
			}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://cubetrackit.quikloc8.com/manuals/dealer-guide.pdf',
		}];
	dealerData.customMapMarker = L.icon({
		iconUrl: '../resources/images/marker-cube.svg',
		iconSize: [40, 40], // size of the icon
		iconAnchor: [20, 39], // point of the icon which will correspond to marker's location
		popupAnchor: [0, -40] // point from which the popup should open relative to the iconAnchor
	});
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-cube';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-cube';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'cube';

	API_URL.ACTIVATION = 'https://activation.cubetrackit.quiktrak.eu/';

} else if (parsedUrl.subdomain === "heli") {
	//} else if (parsedUrl.subdomain === "heli") {
	//console.log('here')
	dealerData.portalName = 'Heli';
	dealerData.name = 'Heli-Portal';
	dealerData.code = 40;
	dealerData.supportCode = 40;
	dealerData.supportPageUrl = 'https://support.heli.gps-secure.co/';
	dealerData.logoSrc = 'https://heli.gps-secure.co/img/logo.png';
	dealerData.logoLetterSrc = 'https://heli.gps-secure.co/img/logo.png';
	dealerData.logoModal = 'https://heli.gps-secure.co/img/logo.png';
	dealerData.logoExternal = 'https://heli.gps-secure.co/img/logo.png';
	dealerData.favicon = 'https://heli.gps-secure.co/img/fav.png';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://heli.gps-secure.co/manuals/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://heli.gps-secure.co/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-heli';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-heli';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'heli';

	API_URL.ACTIVATION = 'https://activation.heli.gps-secure.co/';

} else if (parsedUrl.subdomain === "plantwatch") {
	//} else if (parsedUrl.subdomain === "plantwatch") {
	//console.log('here')
	dealerData.portalName = 'PlantWatch';
	dealerData.name = 'PlantWatch-Portal';
	dealerData.code = 40;
	dealerData.supportCode = 40;
	dealerData.supportPageUrl = 'https://support.plantwatch.gps-secure.co/';
	dealerData.logoSrc = 'https://plantwatch.gps-secure.co/img/logo.png';
	dealerData.logoLetterSrc = 'https://plantwatch.gps-secure.co/img/logo.png';
	dealerData.logoModal = 'https://plantwatch.gps-secure.co/img/logo.png';
	dealerData.logoExternal = 'https://plantwatch.gps-secure.co/img/logo.png';
	dealerData.favicon = 'https://plantwatch.gps-secure.co/img/fav.png';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://plantwatch.gps-secure.co/manuals/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://plantwatch.gps-secure.co/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-plantwatch';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-plantwatch';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'plantwatch';

	API_URL.ACTIVATION = 'https://activation.plantwatch.gps-secure.co/';

} else if (parsedDealer === 'al3rtgps') {
	//} else if (parsedUrl.subdomain === "alert" || parsedUrl.subdomain === "alertgps" || parsedUrl.subdomain === "al3rt") {
	//console.log('here')
	dealerData.portalName = 'Al3rt GPS';
	dealerData.name = 'Al3rtGPS-Portal';
	dealerData.code = 1;
	dealerData.supportCode = 1;
	dealerData.supportPageUrl = 'https://support.al3rtgps.co/?s=1';
	dealerData.logoSrc = 'https://al3rt.gps-secure.co/img/logo.png';
	dealerData.logoLetterSrc = 'https://al3rt.gps-secure.co/img/logo.png';
	dealerData.logoModal = 'https://al3rt.gps-secure.co/img/logo.png';
	dealerData.logoExternal = 'https://al3rt.gps-secure.co/img/logo.png';
	dealerData.favicon = 'https://al3rt.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'https://al3rtgps.co/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'hhttps://cartrack.co/loc8/al3rtgps/Manuals/user-guide-compress.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://cartrack.co/loc8/al3rtgps/Manuals/dealer-guide-compress.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-alertgps';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-alertgps';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'alertgps';

	API_URL.ACTIVATION = 'https://activation.al3rtgps.co/';
} else if (parsedDealer === 'westerngps' || parsedDealer === 'western') {
	//} else if (parsedUrl.subdomain === "western") {
	//console.log('here')
	dealerData.portalName = 'Western GPS';
	dealerData.name = 'WesternGPS-Portal';
	dealerData.code = 30;
	dealerData.supportCode = 30;
	dealerData.supportPageUrl = 'https://support.western.gps-secure.co/';
	dealerData.logoSrc = 'https://western.gps-secure.co/img/logo.png';
	dealerData.logoLetterSrc = 'https://western.gps-secure.co/img/logo.png';
	dealerData.logoModal = 'https://western.gps-secure.co/img/logo.png';
	dealerData.logoExternal = 'https://western.gps-secure.co/img/logo.png';
	dealerData.favicon = 'https://western.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'https://alertgps.quiktrak.eu/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://western.gps-secure.co/manuals/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://western.gps-secure.co/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-westerngps';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-westerngps';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'westerngps';

	API_URL.ACTIVATION = 'https://activation.western.gps-secure.co/';
} else if (parsedUrl.subdomain === "cobra") {
	//} else if (parsedUrl.subdomain === "cobra") {
	//console.log('here')
	dealerData.portalName = 'Cobra Ribs';
	dealerData.name = 'Cobra Ribs-Portal';
	dealerData.isMarine = true;
	dealerData.code = 40;
	dealerData.supportCode = 40;
	dealerData.supportPageUrl = 'https://support.cobra.gps-secure.co/';
	dealerData.logoSrc = 'https://cobra.boatwatch.co/img/logo.png';
	dealerData.logoLetterSrc = 'https://cobra.boatwatch.co/img/logo.png';
	dealerData.logoModal = 'https://cobra.boatwatch.co/img/logo.png';
	dealerData.logoExternal = 'https://cobra.boatwatch.co/img/logo.png';
	dealerData.favicon = 'https://cobra.boatwatch.co/img/fav.png';
	dealerData.agentLoginUrl = 'https://cobra.boatwatch.co';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://cobra.boatwatch.co/manuals/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://cobra.boatwatch.co/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-cobra';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-cobra';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'cobra';

	API_URL.ACTIVATION = 'https://activation.smartostrichfleet.gps-secure.co/';
} else if (parsedDealer === 'smartostrich') {
	//} else if (parsedUrl.subdomain === "smartostrichfleet" || parsedUrl.sld === "smartostrichfleet") {
	//console.log('here')
	dealerData.portalName = 'FleetWatch';
	dealerData.name = 'FleetWatch';
	dealerData.code = 24;
	dealerData.supportCode = 24;
	dealerData.supportPageUrl = 'https://support.smartostrichfleet.com/?s=24';
	dealerData.logoSrc = 'https://cartrack.co/loc8/smartostrich/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/smartostrich/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/smartostrich/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/smartostrich/img/logo.png';
	dealerData.favicon = 'https://smartostrichfleet.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'https://smartostrichfleet.com/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://cartrack.co/manuals/smartostrich/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://smartostrichfleet.gps-secure.co/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-smartostrichfleet';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-smartostrichfleet';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'smartostrichfleet';

	API_URL.ACTIVATION = 'https://activation.smartostrichfleet.com/';
} else if (parsedDealer === 'loc8r') {
	//} else if (parsedUrl.subdomain === "autoprotect" || parsedUrl.sld === "autoprotect") {
	//console.log('here')
	dealerData.portalName = 'Autoprotect';
	dealerData.name = 'Autoprotect';
	dealerData.code = 5;
	dealerData.supportCode = 5;
	dealerData.supportPageUrl = 'https://support.autoprotect.live/?s=5';
	dealerData.logoSrc = 'https://autoprotect.gps-secure.co/img/logo.png';
	dealerData.logoLetterSrc = 'https://autoprotect.gps-secure.co/img/logo.png';
	dealerData.logoModal = 'https://autoprotect.gps-secure.co/img/logo.png';
	dealerData.logoExternal = 'https://autoprotect.gps-secure.co/img/logo.png';
	dealerData.favicon = 'https://autoprotect.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'https://autoprotect.gps-secure.co';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://autoprotect.gps-secure.co/manuals/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://autoprotect.gps-secure.co/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-autoprotect';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-autoprotect';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'autoprotect';

	API_URL.ACTIVATION = 'https://activation.autoprotect.gps-secure.co/';
} else if (parsedUrl.sld === "gps-secure" && parsedUrl.subdomain === "new") {
	//} else if (parsedUrl.sld === "gps-secure" && parsedUrl.subdomain === "new") {
	//console.log('here')
	dealerData.portalName = 'GPS Secure';
	dealerData.name = 'GPS-Secure-Portal';
	dealerData.code = 42;
	dealerData.supportCode = 42;
	dealerData.supportPageUrl = 'https://support.gps-secure.co/';
	dealerData.logoSrc = 'https://new.gps-secure.co/img/logo.png';
	dealerData.logoLetterSrc = 'https://new.gps-secure.co/img/logo.png';
	dealerData.logoModal = 'https://new.gps-secure.co/img/logo.png';
	dealerData.logoExternal = 'https://new.gps-secure.co/img/logo.png';
	dealerData.favicon = 'https://new.gps-secure.co/img/fav.png';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://new.gps-secure.co/manuals/user-guide.pdf',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://new.gps-secure.co/manuals/dealer-guide.pdf',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-gpssecure';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-gpssecure';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'gpssecure';

	API_URL.ACTIVATION = 'https://activation.gps-secure.co/';
 
} else if(parsedDealer === 'witi') {
	dealerData.portalName = 'Witi GPS';
	dealerData.name = 'Witi GPS';
	dealerData.code = 16;
	dealerData.supportCode = 16;
	dealerData.supportPageUrl = 'https://support.witigps.com/?s=16';
	dealerData.logoSrc = 'https://cartrack.co/loc8/witi/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/witi/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/witi/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/witi/img/logo.svg';
	dealerData.favicon = 'https://witi.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'https://loc8.witigps.com/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			//url: 'https://smartostrichfleet.gps-secure.co/manuals/user-guide.pdf',
			url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			//url: 'https://smartostrichfleet.gps-secure.co/manuals/dealer-guide.pdf',

			url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.witigps.com/';
}else if(parsedDealer === 'tekamo') {
	dealerData.portalName = 'TekamoGPS';
	dealerData.name = 'TekamoGPS';
	dealerData.code = 26;
	dealerData.supportCode = 26;
	dealerData.supportPageUrl = 'https://support.tekamogps.co/?s=26';
	dealerData.logoSrc = 'https://cartrack.co/loc8/tekamo/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/tekamo/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/tekamo/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/tekamo/img/logo.svg';
	dealerData.favicon = 'https://tekamo.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'login.tekamogps.com';
	// dealerData.manuals.enduser = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
	// 		//url: 'https://smartostrichfleet.gps-secure.co/manuals/user-guide.pdf',
	// 		url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
	// 	}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
	// 		//url: 'https://smartostrichfleet.gps-secure.co/manuals/dealer-guide.pdf',

	// 		url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.tekamogps.co/';
} else if(parsedDealer === 'ispy') {
	dealerData.portalName = 'iSPY';
	dealerData.name = 'iSPY';
	dealerData.code = 15;
	dealerData.supportCode = 15;
	dealerData.supportPageUrl = 'https://support.ispygps.co/?s=15';
	dealerData.logoSrc = 'https://cartrack.co/loc8/ispy/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/ispy/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/ispy/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/ispy/img/logo.svg';
	dealerData.favicon = 'https://ispy.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'https://ispygps.co/';
	// dealerData.manuals.enduser = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
	// 		//url: 'https://smartostrichfleet.gps-secure.co/manuals/user-guide.pdf',
	// 		url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
	// 	}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
	// 		//url: 'https://smartostrichfleet.gps-secure.co/manuals/dealer-guide.pdf',

	// 		url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.ispygps.co/';
} else if(parsedDealer === 'isstrack') {
	dealerData.portalName = 'Ignition Security';
	dealerData.name = 'Ignition Security';
	dealerData.code = 14;
	dealerData.supportCode = 14;
	dealerData.supportPageUrl = 'https://support.ispygps.co/?s=14';
	dealerData.logoSrc = 'https://cartrack.co/loc8/isstrack/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/isstrack/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/isstrack/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/isstrack/img/logo.svg';
	dealerData.favicon = 'https://isstrack.gps-secure.co/img/fav.png';
	dealerData.agentLoginUrl = 'http://isstrack.com.au/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			//url: 'https://smartostrichfleet.gps-secure.co/manuals/user-guide.pdf',
			url: 'https://cartrack.co/manuals/isstrack/Manual(Eng).pdf'
		}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
	// 		//url: 'https://smartostrichfleet.gps-secure.co/manuals/dealer-guide.pdf',

	// 		url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.ignition.quiktrak.eu/';
}   else if(parsedDealer === 'cyclops') {
	dealerData.portalName = 'Cyclops Security Systems';
	dealerData.name = 'Cyclops Security Systems';
	dealerData.code = 11;
	dealerData.supportCode = 11;
	dealerData.supportPageUrl = 'https://support.quiktrak.au/?s=11';
	dealerData.logoSrc = 'https://cartrack.co/loc8/cyclops/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/cyclops/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/cyclops/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/cyclops/img/logo.svg';
	dealerData.favicon = 'https://cartrack.co/loc8/cyclops/img/fav.ico';
	dealerData.agentLoginUrl = 'https://cartrack.co/loc8/cyclops/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			//url: 'https://smartostrichfleet.gps-secure.co/manuals/user-guide.pdf',
			url: 'https://cartrack.co/loc8/cyclops/Manuals/user-guide.pdf'
		}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
	// 		//url: 'https://smartostrichfleet.gps-secure.co/manuals/dealer-guide.pdf',

	// 		url: 'https://cartrack.co/manuals/witi/software-user-manual.pdf'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.cyclops.quiktrak.eu/';
} else if(parsedDealer === 'geelinx') {
	dealerData.portalName = 'GeelinxGPS';
	dealerData.name = 'GeelinxGPS';
	dealerData.code = 13;
	dealerData.supportCode = 13;
	dealerData.supportPageUrl = 'https://support.quiktrak.au/?s=13';
	dealerData.logoSrc = 'https://cartrack.co/loc8/geelinx/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/geelinx/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/geelinx/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/geelinx/img/logo.png';
	//dealerData.favicon = 'https://cartrack.co/loc8/cyclops/img/fav.ico';
	dealerData.agentLoginUrl = 'https://cartrack.co/loc8/geelinx/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/loc8/geelinx/Manuals/user-guide.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
 

			url: 'https://cartrack.co/loc8/geelinx/Manuals/dealer-guide.pdf'
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.geelinxgps.quiktrak.eu/';
}  else if(parsedDealer === 'nutech') {
	dealerData.portalName = 'Tracktech by Nutech GPS';
	dealerData.name = 'Tracktech by Nutech GPS';
	dealerData.code = 18;
	dealerData.supportCode = 18;
	dealerData.supportPageUrl = 'https://support.nutechgps.com/?s=18';
	dealerData.logoSrc = 'https://cartrack.co/loc8/nutech/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/nutech/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/nutech/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/nutech/img/logo.svg';
	//dealerData.favicon = 'https://cartrack.co/loc8/cyclops/img/fav.ico';
	dealerData.agentLoginUrl = 'https://nutechgps.com/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/loc8/nutech/Manuals/user-guide.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
 

			url: 'https://cartrack.co/loc8/nutech/Manuals/dealer-guide.pdf'
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.nutechgps.com/';
} else if(parsedDealer === 'fridgewatch') {
	dealerData.portalName = 'FridgeWatch';
	dealerData.name = 'FridgeWatch';
	dealerData.code = 12;
	dealerData.supportCode = 12;
	dealerData.supportPageUrl = 'https://support.quiktrak.au/?s=12';
	dealerData.logoSrc = 'https://cartrack.co/loc8/fridgewatch/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/fridgewatch/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/fridgewatch/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/fridgewatch/img/logo.png';
	dealerData.favicon = 'https://cartrack.co/loc8/fridgewatch/img/fav.png';
	dealerData.agentLoginUrl = 'https://cartrack.co/loc8/fridgewatch/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/loc8/fridgewatch/Manuals/user-guide.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
 

			url: 'https://cartrack.co/loc8/fridgewatch/Manuals/dealer-guide.pdf'
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.fridgewatch.quiktrak.eu/';
} else if(parsedDealer === 'boatwatch') {
	dealerData.portalName = 'BoatWatch';
	dealerData.name = 'BoatWatch';
	dealerData.code = 22;
	dealerData.supportCode = 22;
	dealerData.supportPageUrl = 'https://support.boatwatch.co/?s=22';
	dealerData.logoSrc = 'https://cartrack.co/loc8/boatwatch/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/boatwatch/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/boatwatch/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/boatwatch/img/logo.svg';
//	dealerData.favicon = 'https://cartrack.co/loc8/fridgewatch/img/fav.png';
	dealerData.agentLoginUrl = 'https://boatwatch.co/';
	// dealerData.manuals.enduser = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
			 
	// 		url: 'https://cartrack.co/loc8/fridgewatch/Manuals/user-guide.pdf'
	// 	}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
 

	// 		url: 'https://cartrack.co/loc8/fridgewatch/Manuals/dealer-guide.pdf'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.boatwatch.co/';
} 
else if(parsedDealer === 'tac') {
	dealerData.portalName = 'TAC';
	dealerData.name = 'TAC';
	dealerData.code = 6;
	dealerData.supportCode = 6;
	dealerData.supportPageUrl = 'https://support.pvstrack.com/?s=6';
	dealerData.logoSrc = 'https://cartrack.co/loc8/tac/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/tac/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/tac/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/tac/img/logo.png';
//	dealerData.favicon = 'https://cartrack.co/loc8/fridgewatch/img/fav.png';
	dealerData.agentLoginUrl = 'https://cartrack.co/loc8/tac/';
	// dealerData.manuals.enduser = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
			 
	// 		url: 'https://cartrack.co/loc8/fridgewatch/Manuals/user-guide.pdf'
	// 	}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
 

	// 		url: 'https://cartrack.co/loc8/fridgewatch/Manuals/dealer-guide.pdf'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	//API_URL.ACTIVATION = 'https://activation.boatwatch.co/';
} else if(parsedDealer === 'vtrac') {
	dealerData.portalName = 'Vtrac';
	dealerData.name = 'Vtrac';
	dealerData.code = 38;
	dealerData.supportCode = 38;
	dealerData.supportPageUrl = 'https://support.quiktrak.au/?s=38';
	dealerData.logoSrc = 'https://cartrack.co/loc8/vtrac/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/vtrac/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/vtrac/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/vtrac/img/logo.png';
//	dealerData.favicon = 'https://cartrack.co/loc8/fridgewatch/img/fav.png';
	dealerData.agentLoginUrl = 'https://cartrack.co/loc8/vtrac/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/loc8/vtrac/Manuals/user-guide.pdf'
		}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
 

	// 		url: 'https://cartrack.co/loc8/fridgewatch/Manuals/dealer-guide.pdf'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.quiktrak.au/';
} else if(parsedDealer === 'ufind') {
	dealerData.portalName = 'UFind';
	dealerData.name = 'UFind';
	dealerData.code = 28;
	dealerData.supportCode = 28;
	dealerData.supportPageUrl = 'https://support.ufindgps.co/?s=28';
	dealerData.logoSrc = 'https://cartrack.co/loc8/ufind/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/ufind/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/ufind/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/ufind/img/logo.svg';
//	dealerData.favicon = 'https://cartrack.co/loc8/fridgewatch/img/fav.png';
	dealerData.agentLoginUrl = 'https://cartrack.co/loc8/ufind/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/manuals/ufind/user-guide.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
 

			url: 'https://cartrack.co/manuals/ufind/dealer-guide.pdf'
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.ufindgps.co/';
} else if(parsedDealer === 'warden') {
	dealerData.portalName = 'Warden';
	dealerData.name = 'Warden';
	dealerData.code = 29;
	dealerData.supportCode = 29;
	dealerData.supportPageUrl = 'https://support.wardengps.com/?s=29';
	dealerData.logoSrc = 'https://cartrack.co/loc8/warden/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/warden/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/warden/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/warden/img/logo.png';
//	dealerData.favicon = 'https://cartrack.co/loc8/fridgewatch/img/fav.png';
	dealerData.agentLoginUrl = 'https://wardengps.com/';
	// dealerData.manuals.enduser = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
			 
	// 		url: 'https://cartrack.co/manuals/ufind/user-guide.pdf'
	// 	}];
	// dealerData.manuals.dealer = [
	// 	{
	// 		name: LANGUAGE.HOME_MSG028,
 

	// 		url: 'https://cartrack.co/manuals/ufind/dealer-guide.pdff'
	// 	}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.wardengps.com/';
} else if(parsedDealer === 'pillalogps') {
	dealerData.portalName = 'PillaloGPS';
	dealerData.name = 'PillaloGPS';
	 dealerData.code = 19;
	 dealerData.supportCode = 19;
	dealerData.supportPageUrl = 'https://support.pillalogps.com/?s=19';
	dealerData.logoSrc = 'https://cartrack.co/loc8/pillalogps/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/pillalogps/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/pillalogps/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/pillalogps/img/logo.png';
//	dealerData.favicon = 'https://cartrack.co/loc8/fridgewatch/img/fav.png';
	dealerData.agentLoginUrl = 'https://pillalogps.com/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/loc8/pillalogps/Manuals/user-guide.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
 

			url: 'https://cartrack.co/loc8/pillalogps/Manuals/dealer-guide.pdf'
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-gpssecure';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-gpssecure';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'gpssecure';

	API_URL.ACTIVATION = 'https://activation.pillalogps.com/';
} else if(parsedDealer === 'reconogps') {
	dealerData.portalName = 'ReconoGPS';
	dealerData.name = 'ReconoGPS';
	 dealerData.code = 98;
	 dealerData.supportCode = 98;
	dealerData.supportPageUrl = 'https://support.reconogps.com/?s=98';
	dealerData.logoSrc = 'https://cartrack.co/loc8/reconogps/img/logo.png';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/reconogps/img/logo.png';
	dealerData.logoModal = 'https://cartrack.co/loc8/reconogps/img/logo.png';
	dealerData.logoExternal = 'https://cartrack.co/loc8/reconogps/img/logo.png';
	dealerData.favicon = 'https://cartrack.co/loc8/reconogps/img/fav.png';
	dealerData.agentLoginUrl = 'https://cartrack.co/loc8/reconogps';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/manuals/reconogps/user-guide.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
 

			url: 'https://cartrack.co/manuals/reconogps/dealer-guide.pdf'
		}];
	/*dealerData.customMapMarker = L.icon({
		iconUrl: '../resources/images/marker-reconogps.svg',
		iconSize: [40, 40], // size of the icon
		iconAnchor: [20, 39], // point of the icon which will correspond to marker's location
		popupAnchor: [0, -40] // point from which the popup should open relative to the iconAnchor
	});*/
	
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-reconogps';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-reconogps';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'reconogps';

	API_URL.ACTIVATION = 'https://activationreconogps.cartrack.co/';
} else if(parsedDealer === 'vizn') {
	dealerData.portalName = 'VIZN';
	dealerData.name = 'VIZN';
	dealerData.code = 34;
	dealerData.supportCode = 34;
	dealerData.supportPageUrl = 'https://support.vizngps.co/';
	dealerData.logoSrc = 'https://cartrack.co/loc8/vizn/img/logo.svg';
	dealerData.logoLetterSrc = 'https://cartrack.co/loc8/vizn/img/logo.svg';
	dealerData.logoModal = 'https://cartrack.co/loc8/vizn/img/logo.svg';
	dealerData.logoExternal = 'https://cartrack.co/loc8/vizn/img/logo.svg';
	dealerData.favicon = 'https://activation.vizngps.co/images/favicon-live.png';
	dealerData.agentLoginUrl = 'hhttps://vizngps.co/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			 
			url: 'https://cartrack.co/loc8/vizn/Manuals/user-guide.pdf'
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
 

			url: 'https://cartrack.co/loc8/vizn/Manuals/dealer-guide.pdf'
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-classic';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-classic';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'classic';

	API_URL.ACTIVATION = 'https://activation.vizngps.co/';
} 


//let parsedPath = window.location.pathname.split('/')[1]
//let parsedDealer = window.location.pathname.split('/')[2]
//console.log(parsedDealer)
/*if (parsedDealer == 'fridgewatch') {
	dealerData.portalName = 'FridgeWatch';
	dealerData.name = 'FridgeWatch-Portal';
	dealerData.code = 47;
	dealerData.supportCode = 47;
	dealerData.supportPageUrl = 'http://forgot.quiktrak.eu/password/';
	dealerData.logoSrc = 'https://gps-secure.co/fridgewatch/img/logo.png';
	dealerData.logoLetterSrc = 'https://gps-secure.co/fridgewatch/img/logo.png';
	dealerData.logoModal = 'https://gps-secure.co/fridgewatch/img/logo.png';
	dealerData.logoExternal = 'https://gps-secure.co/fridgewatch/img/logo.png';
	dealerData.favicon = 'https://fridgewatch.quiktrak.co/Attached/WebSites/FridgeWatch/img/fav.ico';
	dealerData.agentLoginUrl = 'http://fridgewatch.net.au/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://fridgewatch.quiktrak.co/Attached/WebSites/FridgeWatch/manuals/Manual(Engl)-compress.pdf',
		}];

	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-fridgewatch';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-fridgewatch';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'fridgewatch';

	API_URL.ACTIVATION = 'https://activation.fridgewatch.quiktrak.eu/';

} else if (parsedDealer == 'nutech') {

	dealerData.portalName = 'NuTech';
	dealerData.name = 'NuTech-Portal';
	dealerData.code = 42;
	dealerData.supportCode = 42;
	dealerData.supportPageUrl = 'http://forgot.quiktrak.eu/password/';
	dealerData.logoSrc = 'https://gps-secure.co/nutech/img/logo.svg';
	dealerData.logoLetterSrc = 'https://gps-secure.co/nutech/img/logo.svg';
	dealerData.logoModal = 'https://gps-secure.co/nutech/img/logo.svg';
	dealerData.logoExternal = 'https://gps-secure.co/nutech/img/logo.svg';
	dealerData.favicon = 'https://fridgewatch.quiktrak.co/Attached/WebSites/NuTech/img/fav.ico';
	dealerData.agentLoginUrl = 'http://nutechgps.com/';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: 'https://nutech.quiktrak.co/Attached/WebSites/nutech/manuals/Manual(Engl)-compress.pdf',

	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-nutech';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-nutech';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'nutech';

	API_URL.ACTIVATION = '';
}else if(parsedDealer == 'westerngps'){
	dealerData.portalName = 'Western GPS';
	dealerData.name = 'WesternGPS-Portal';
	dealerData.code = 55;
	dealerData.supportCode = 55;
	dealerData.supportPageUrl = '';
	dealerData.logoSrc = '';
	dealerData.logoLetterSrc = '';
	dealerData.logoModal = '';
	dealerData.logoExternal = '';
	dealerData.favicon = '';
	dealerData.agentLoginUrl = '';
	dealerData.manuals.enduser = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: '',
		}];
	dealerData.manuals.dealer = [
		{
			name: LANGUAGE.HOME_MSG028,
			url: '',
		}];
	document.title = dealerData.portalName;
	$$("link[rel*='icon']").attr("href", dealerData.favicon);
	Template7.global.DEALER_TEXT_COLOR_CLASS = 'text-color-westerngps';
	Template7.global.DEALER_BG_COLOR_CLASS = 'bg-color-westerngps';
	Template7.global.DEALER_PRELOADER_COLOR_CLASS = 'westerngps';

	API_URL.ACTIVATION = '';
}*/









Template7.global.IS_MARINE = dealerData.isMarine;

var htmlTemplate = $$('script#loginScreenTemplate').html();
var compiledTemplate = Template7.compile(htmlTemplate);
var withContext = compiledTemplate(dealerData);
$('#app').prepend(withContext);

//DATATABLES Global  Settings
$.extend(true, $.fn.dataTable.defaults, {
	scrollX: true,
	//scrollY: true
});


// Framework7 App main instance
var app = new Framework7({
	root: '#app', // App root element
	id: 'portal.quikloc8.com', // App bundle ID
	name: dealerData.portalName, // App name
	theme: 'md', // Automatic theme detection
	view: {
		stackPages: true,
		//pushState: true,
		//pushStateRoot: document.location.pathname,
	},
	// Enable panel left visibility breakpoint
	panel: {
		leftBreakpoint: 960,
	},
	input: {
		scrollIntoViewOnFocus: true,
		scrollIntoViewCentered: true,
	},
	notification: {
		//title: self.name,
		icon: '<img src="../resources/images/favicon.png" class="icon-notification" alt="" />',
		closeTimeout: 3000,
	},
	// App root data
	data: function () {
		var maxPopupWidth = 280;
		if (this.device.desktop) {
			maxPopupWidth = 300;
		}

		return {
			AppDetails: dealerData,
			DEMOACCONTS: ['demochile'],
			MaxMapPopupWidth: maxPopupWidth,
			PolygonCustomization: {
				color: '#AA5959',
				fillColor: '#FF0000',
				fillOpacity: 0.25,
			},
			PolylineCustomization: {
				mainBg: {
					//color: '#f44336',
					color: '#039ac5',
					weight: 6,
					opacity: 0.8,
				},
				main: {
					//color: '#f96868',
					color: '#00b9ee',
					weight: 3,
					opacity: 0.8,
				},
				droppedBg: {
					//color: '#b50000',     //red
					color: '#b47605',   //orange
					weight: 6,
					opacity: 0.8,
				},
				dropped: {
					//color: '#fc0405',
					color: '#fd9a08',   //orange
					weight: 3,
					opacity: 0.8,
				},
				boundariesBg: {
					color: '#6199CC',
					weight: 6,
					opacity: 0.8,
				},
				boundaries: {
					color: '#00B1FC',
					weight: 3,
					opacity: 0.8,
				},
			},
			PolylineCustomizationSemi: {
				mainBg: {
					//color: '#f44336',
					color: '#039ac5',
					weight: 6,
					opacity: 0.8,
				},
				main: {
					//color: '#f96868',
					color: '#00b9ee',
					weight: 3,
					opacity: 0.8,
				},
				droppedBg: {
					//color: '#b50000',     //red
					color: '#b47605',   //orange
					weight: 6,
					opacity: 0.8,
				},
				dropped: {
					//color: '#fc0405',
					color: '#fd9a08',   //orange
					weight: 3,
					opacity: 0.8,
				},
				boundariesBg: {
					color: '#6199CC',
					weight: 6,
					opacity: 0.8,
				},
				boundaries: {
					color: '#00B1FC',
					weight: 3,
					opacity: 0.8,
				},
			},
			ChartCustomization: {
				colors: ['#4dc08e', '#f96868', '#f9b256', '#00b9ee', '#5972b6', '#c693c2', '#f28d4f', '#303030', '#009a93', '#857c13'],
				colorStates: {
					good: '#4dc08e',
					attention: '#f28d4f',
					warning: '#f96868'
				}
			},
			TripCustomization: {
				colors: ['#4dc08e', '#f96868', '#f9b256', '#00b9ee', '#5972b6', '#c693c2', '#f28d4f', '#303030', '#009a93', '#857c13', '#ff59ac', '#ff5975', '#004899', '#7a0727', '#9185be'],
				colorNames: ['color-1', 'color-2', 'color-3', 'color-4', 'color-5', 'color-6', 'color-7', 'color-8', 'color-9', 'color-10', 'color-11', 'color-12', 'color-13', 'color-14', 'color-15',]
			},
			UTCOFFSET: moment().utcOffset(),
			AccountSolutionArray: [],
			CustomerType: '',
			BottomWidgetAssetImei: '',
		};
	},
	on: {
	 
		routerAjaxStart: function () {
			app.progressbar.show();
	 
		},
		routerAjaxComplete: function () {
			app.progressbar.hide();
		},
		init: function () {
			var self = this;
			

			
			let url = self.data.AppDetails.logoLetterSrc;
			let pattern = /^http/i;

			if (!pattern.test(url)) {
				url = self.data.AppDetails.loginUrl + url;
			}

			//console.log(self.data.AppDetails.loginUrl+self.data.AppDetails.logoLetterSrc)
			self.methods.getBase64FromImageUrl(url, function (imgBase64) {

				self.data.AppDetails.logoBase64 = imgBase64;
			});

 

			try {
				window.localStorage.setItem('test', 'test')
			} catch (e) {
				self.methods.customDialog({ title: LANGUAGE.COM_MSG123, text: LANGUAGE.PROMPT_MSG0123, noLogo: true })
				console.log(e)
			}

			 	
				  if(localStorage.ACCOUNT && localStorage.PASSWORD) {
					  //~~~self.methods.login();
				  }
				  else {
					  self.methods.logout();
				  }
		},
	},
	// App root methods
	methods: {
		capitalize: function (s) {
			if (typeof s !== 'string') return ''
			return s.charAt(0).toUpperCase() + s.slice(1)
		},
		isJsonString: function (str) {
			try { var ret = JSON.parse(str); } catch (e) { return false; } return ret;
		},
		findObjectByKey: function (array, key, value) {
			for (var i = 0; i < array.length; i++) {
				if (array[i][key] == value) {
					return array[i];
				}
			}
			return null;
		},
		isObjEmpty: function (obj) {
			/*for (var key in obj) {
					  return false;
				  }
				  return true;*/
			// null and undefined are "empty"
			if (obj == null) return true;

			// Assume if it has a length property with a non-zero value
			// that that property is correct.
			if (obj.length > 0) return false;
			if (obj.length === 0) return true;

			// If it isn't an object at this point
			// it is empty, but it can't be anything *but* empty
			// Is it empty?  Depends on your application.
			if (typeof obj !== "object") return true;

			// Otherwise, does it have any properties of its own?
			// Note that this doesn't handle
			// toString and valueOf enumeration bugs in IE < 9
			for (var key in obj) {
				if (hasOwnProperty.call(obj, key)) return false;
			}

			return true;
		},
		getBase64FromImageUrl: function (url, callback) {
			//console.log(url);
			var img = new Image();
			img.crossOrigin = "anonymous";
			img.onload = function () {
				var canvas = document.createElement("canvas");
				canvas.width = this.width;
				canvas.height = this.height;
				var ctx = canvas.getContext("2d");
				ctx.drawImage(this, 0, 0);
				var dataURL = canvas.toDataURL("image/png");

				//return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

				//dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
				callback(dataURL);
			};
			img.src = url;
		},
		reverseArry: function (arry) {
			var newArry = [];
			var i = null;
			for (i = arry.length - 1; i >= 0; i -= 1) {
				newArry.push(arry[i]);
			}
			return newArry;
		},
		getCountOfObjectvalues: function (obj) {
			let ret = 0;
			if (!this.methods.isObjEmpty(obj)) {
				let keys = Object.keys(obj);
				for (const key of keys) {
					obj[key] += '';
					if (obj[key] && obj[key] != '0') {
						ret += parseInt(obj[key], 10);
					}
				}
			}
			return ret;
		},
		sortArrayByObjProps: function (list, sortBy) {
			//sortBy.direction == 1  means asc
			//sortBy.direction == -1 means desc
			if (list && list.length) {
				list.sort(function (a, b) {
					let i = 0, result = 0;
					while (i < sortBy.length && result === 0) {
						result = sortBy[i].direction * (a[sortBy[i].prop].toString().toUpperCase() < b[sortBy[i].prop].toString().toUpperCase() ? -1 : (a[sortBy[i].prop].toString().toUpperCase() > b[sortBy[i].prop].toString().toUpperCase() ? 1 : 0));
						i++;
					}
					return result;
				})
			}
			return list;
		},
		convertTimZoneValToZZformat: function (val) {
			let ret = '';
			val = parseFloat(val);
			val >= 0 ? ret = '+' : ret = '-';
			if (val < 10 && val >= 0 ||
				val < 0 && val > -10) {
				ret += '0';
			}

			val = Math.abs(val);
			if (Number.isInteger(val)) {
				ret += val;
			} else {
				ret += parseInt(val);
				ret += parseInt(val.toString().split('.')[1]) / 100 * 60;
			}
			ret = ret.padEnd(5, '0');

			return ret;
		},
		findTimeZoneNameByOffset: function (offset) {
			let ret = '';
			let index = moment.tz.names().findIndex(timezoneName => moment.tz(timezoneName).format('ZZ') === offset);
			if (index !== -1) {
				ret = moment.tz.names()[index];
			}
			return ret;
		},
		setAccountToLocalDB: function (storage_account) {
			$.ajax({
				type: "POST",
				url: "../resources/php/account.php",
				dataType: 'json',
				data: JSON.stringify({ storage_account }),
				async: true,
				cache: false,
				beforeSend: function () {

				},
				success: function (data) {
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					console.log(XMLHttpRequest);
					console.log(textStatus);
					console.log(errorThrown);
				}
			});
		},
		setToLocalDB: function (storage_name, storage_data) {
			let self = this
			//console.log('storage_data',storage_data)
			let parsed_data = storage_data?.split("'")
				.join("")
			$.ajax({
				type: "POST",
				url: "../resources/php/set.php",
				dataType: 'json',
				data: JSON.stringify({ storage_name, storage_account: localStorage.ACCOUNT, storage_data: JSON.parse(parsed_data) }),
				async: true,
				cache: false,
				beforeSend: function () {

				},
				success: function (data) {
				},
				error: function (XMLHttpRequest, textStatus, errorThrown) {
					console.log(XMLHttpRequest);
					console.log(textStatus);
					console.log(errorThrown);

					if(XMLHttpRequest.status === 500) {
						self.methods.customDialog({ text: LANGUAGE.PROMPT_MSG0145 });
					}
				}
			});
		},
		getFromLocalDB: function (storage_name) {

			return new Promise((resolve, reject) => {
				$.ajax({
					type: "POST",
					url: "../resources/php/get.php",
					dataType: 'json',
					data: JSON.stringify({ storage_name, storage_account: localStorage.ACCOUNT }),
					async: true,
					cache: false,
					beforeSend: function () {

					},
					success: function (data) {

						if (data) {
							ret = JSON.parse(data?.data[0]?.storage_data
								.split("\r\n")
								.join(",")
								.split("\r")
								.join(",")
								.split("\n")
								.join(",")
								.split("\t")
								.join(",")
								.split("<br>")
								.join(",")
								.split(",")).storage_data;
							resolve(ret)
						}
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						console.log(XMLHttpRequest);
						console.log(textStatus);
						console.log(errorThrown);
					}
				});
			})

		},
		getFromDBStorage: async function (name) {
			let self = this;
			//console.log('get ' + name)
			var ret = [];
			var str = '';
			if (name) {
				switch (name) {
					case 'reportDataDB':
						ret = await self.methods.getFromLocalDB("COM.QUIKTRAK.QUIKLOC8.REPORTDATADB")
						break;
					default:
						self.dialog.alert('There is no item saved with such name - ' + name);
				}
			} else {
				self.dialog.alert('Wrong query parameters!');
			}
			return ret;
		},
		getFromStorage: function (name) {
			let self = this;
			//console.log('get ' + name)
			var ret = [];
			var str = '';
			if (name) {
				switch (name) {
					case 'userInfo':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.USERINFO");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'assetList':
						//self.methods.getFromLocalDB("COM.QUIKTRAK.QUIKLOC8.ASSETLIST").then(result => {ret = result; console.log('assets', result);return ret;})
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.ASSETLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'templateList': 
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.TEMPLATELIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'groupList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.GROUPLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'usersList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.USERSLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'contactList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.CONTACTLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'taskList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.TASKLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;
					
					case 'customerList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.CUSTOMERLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;
						
					case 'customerInfo':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.CUSTOMERINFO");
						if (str) {
							ret = JSON.parse(str);
						}
						break;


					case 'geofenceList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.GEOFENCELIST");
						if (str) {
							ret = JSON.parse(str);
						} else {
							ret = {};
						}
						break;

					case 'intervalRemindersList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.INTERVALREMINDERS");
						if (str) {
							ret = JSON.parse(str);
						} else {
							ret = {};
						}
						break;
						case 'POIList':
						str = localStorage.getItem("COM.QUIKTRAK.NEW.POILIST");
						ret = str ? JSON.parse(str) : [];
						break;


					case 'notifications':

						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.NOTIFICATIONS");
						if (str) {
							ret = JSON.parse(str);
						} else {
							ret = {};
						}
						break;

					case 'permissions2':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.PERMISSIONS2");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'historyArray':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.HISTORYARRAY");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'historyEvents':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.EVENTSARRAY");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'reportData':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.REPORTDATA");
						if (str) {
							ret = JSON.parse(str);
						}
						break;
						case 'reportDataTrips':
							str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.REPORTDATATRIPS");
							if (str) {
								ret = JSON.parse(str);
							}
							break;
					case 'dashboard':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.DASHBOARD");
						if (str) {
							ret = JSON.parse(str);
						} else {
							ret = {};
						}
						break;

					case 'solutions':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.SOLUTIONS");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'alertList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.ALERTLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'scheduledReportList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.SCHEDULEDREPORTS");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'mapSettings':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.MAPSETTINGS");
						if (str) {
							ret = JSON.parse(str);
						} else {
							ret = {};
						}
						break;

					case 'otherSettings':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.OTHERSETTINGS");
						if (str) {
							ret = JSON.parse(str);
						} else {
							ret = {};
						}
						break;

					case 'assetTypes':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.ASSETTYPES");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					case 'userAlarmSettings':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.USERALARMSETTINGS");
						if (str) {
							ret = JSON.parse(str);
						} else {
							ret = {};
						}
						break;
						
					case 'alarmPhotoList':
						str = localStorage.getItem("COM.QUIKTRAK.QUIKLOC8.ALARMPHOTOLIST");
						if (str) {
							ret = JSON.parse(str);
						}
						break;

					default:
						self.dialog.alert('There is no item saved with such name - ' + name);
				}
			} else {
				self.dialog.alert('Wrong query parameters!');
				console.log(name);
			}
			return ret;
		},
		setInStorage: function (params) {
			let self = this;
			if (typeof (params) == 'object' && params.name) {
				switch (params.name) {
					case 'userInfo':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.USERINFO", JSON.stringify(params.data));
						break;

					case 'groupList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.GROUPLIST", JSON.stringify(params.data));
						break;
					case 'taskList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.TASKLIST", JSON.stringify(params.data));
						break;

					case 'contactList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.CONTACTLIST", JSON.stringify(params.data));
						break;

					case 'customerList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.CUSTOMERLIST", JSON.stringify(params.data));
						break;

					case 'customerInfo':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.CUSTOMERINFO", JSON.stringify(params.data));
						break;


					case 'usersList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.USERSLIST", JSON.stringify(params.data));
						break;
					case 'templateList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.TEMPLATELIST", JSON.stringify(params.data));
						break;

					case 'geofenceList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.GEOFENCELIST", JSON.stringify(params.data));
						break;

					case 'intervalRemindersList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.INTERVALREMINDERS", JSON.stringify(params.data));
						break;
						case 'POIList':
							localStorage.setItem("COM.QUIKTRAK.NEW.POILIST", JSON.stringify(params.data));
							break;

					case 'historyArray':
						var HistoryArray = self.methods.parsePlaybackHystoryArr(params.data);

						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.HISTORYARRAY", JSON.stringify(HistoryArray));
						break;

					case 'historyEvents':
						var EventsArray = self.methods.parsePlaybackEventsArr(params.data);

						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.EVENTSARRAY", JSON.stringify(EventsArray));
						break;

					case 'reportData':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.REPORTDATA", JSON.stringify(params.data));
						break;
						case 'reportDataTrips':
							localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.REPORTDATATRIPS", JSON.stringify(params.data));
							break;
					case 'reportDataDB':
						self.methods.setToLocalDB("COM.QUIKTRAK.QUIKLOC8.REPORTDATADB", JSON.stringify(params.data));
						break;

					case 'dashboard':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.DASHBOARD", JSON.stringify(params.data));
						break;

					case 'solutions':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.SOLUTIONS", JSON.stringify(params.data));
						break;

					case 'alertList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.ALERTLIST", JSON.stringify(params.data));
						break;

					case 'scheduledReportList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.SCHEDULEDREPORTS", JSON.stringify(params.data));
						break;

					case 'mapSettings':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.MAPSETTINGS", JSON.stringify(params.data));
						break;
					case 'otherSettings':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.OTHERSETTINGS", JSON.stringify(params.data));
						break;
					case 'assetTypes':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.ASSETTYPES", JSON.stringify(params.data));
						break;
					case 'userAlarmSettings':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.USERALARMSETTINGS", JSON.stringify(params.data));
						break;
					case 'permissions2':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.PERMISSIONS2", JSON.stringify(params.data));
						break;
					case 'alarmPhotoList':
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.ALARMPHOTOLIST", JSON.stringify(params.data));
						break;


					default:
						self.dialog.alert('There is no function associated with this name - ' + params.name);
				}
			} else {
				self.dialog.alert('Wrong query parameters!');
				console.log(params);
			}
		},
		parsePlaybackHystoryArr: function (arry) {
			let self = this;
			let newArry = [];
			//var userInfo = app.methods.getFromStorage('userInfo');
						
			if (arry && arry.length) {
				for (var i = arry.length - 1; i >= 0; i--) {
					if (JSON.stringify(arry[i]) !== JSON.stringify(arry[i - 1])) {
						var index = 0;
						//console.log(arry[i][index++], moment(arry[i][index++],'DD/MM/YYYY HH:mm:ss') )
						//let newPosDateTime = moment(arry[i][index++],'DD/MM/YYYY HH:mm:ss').utc().add(userInfo.UserInfo.TimeZone, 'hours').add(app.data.UTCOFFSET,'minutes').format('DD/MM/YYYY HH:mm:ss');
	               	
						var point = {
							positionTime: arry[i][index++],
							lat: arry[i][index++],
							lng: arry[i][index++],
							direct: arry[i][index++],
							speed: arry[i][index++],
							timeSpan: arry[i][index++],
							mileage: arry[i][index++],
							alerts: arry[i][index++],
							status: arry[i][index++],
							noname1: arry[i][index++],
							noname2: arry[i][index++],
							battery: arry[i][index++],//added
							
						};
						
						
						if(!point.lat.toString().includes('22.675') && !point.lng.toString().includes('113.972')){
							newArry.push(point);
						}
					}
				}
				newArry = self.methods.reverseArry(newArry);
			}
			return newArry;
		},
		parsePlaybackEventsArr: function (arry) {
			let self = this;
			let newArry = [];
			if (arry && arry.length) {
				for (var i = arry.length - 1; i >= 0; i--) {
					if (JSON.stringify(arry[i]) !== JSON.stringify(arry[i - 1])) {
						var index = 0;
						var point = {
							assetID: arry[i][index++],
							eventClass: arry[i][index++],
							eventType: arry[i][index++],
							state: arry[i][index++],
							otherCode: arry[i][index++],
							otherCode2: arry[i][index++],
							contactCode: arry[i][index++],
							beginTime: arry[i][index++],
							endTime: arry[i][index++],
							positionType: arry[i][index++],
							lat: arry[i][index++],
							lng: arry[i][index++],
							alt: arry[i][index++],//bat
							alerts: arry[i][index++],
							status: arry[i][index++],
							content: arry[i][index++],
						};
						if(!point.lat.toString().includes('22.675') && !point.lng.toString().includes('113.972')){
							newArry.push(point);
						}
					}
				}
				newArry = self.methods.reverseArry(newArry);
			}
			return newArry;
		},

		guid: function () {
			function S4() {
				return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
			}
			return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
		},
		getPlusInfo: function () {
			var self = this;

			var uid = self.methods.guid();
			if (window.device) {
				if (!localStorage.PUSH_MOBILE_TOKEN) {
					localStorage.PUSH_MOBILE_TOKEN = uid;
				}
				localStorage.PUSH_APP_KEY = BuildInfo.packageName;
				localStorage.PUSH_APPID_ID = BuildInfo.packageName;
				localStorage.DEVICE_TYPE = device.platform;
			} else {
				if (!localStorage.PUSH_MOBILE_TOKEN)
					localStorage.PUSH_MOBILE_TOKEN = uid;
				if (!localStorage.PUSH_APP_KEY)
					localStorage.PUSH_APP_KEY = self.id;
				if (!localStorage.PUSH_DEVICE_TOKEN)
					localStorage.PUSH_DEVICE_TOKEN = uid;
				//localStorage.PUSH_DEVICE_TOKEN = "75ba1639-92ae-0c4c-d423-4fad1e48a49d"
				localStorage.PUSH_APPID_ID = self.id;
				localStorage.DEVICE_TYPE = "browser";
			}
		},
		hideKeyboard: function () {
			document.activeElement.blur();
			$$("input").blur();
		},
		openExternal: function (href) {
			/*if (this.device.ios){
					  window.open(href, '_blank', 'location=yes');
				  }else{
					  if (typeof navigator !== "undefined" && navigator.app) {
						  navigator.app.loadUrl(href, { openExternal: true });
					  } else {
						  window.open(href, '_blank');
					  }
				  }*/
			window.open(href, '_blank');
		},
		goForSupport: function () {
			var self = this;

			var userInfo = self.methods.getFromStorage('userInfo').UserInfo;
			var data = {
				name: '',
				loginName: '',
				email: '',
				phone: '',
				s: self.data.AppDetails.supportCode,
			};

			if (userInfo.FirstName) {
				data.name = userInfo.FirstName.trim();
			}
			if (userInfo.SurName) {
				data.name = data.name + ' ' + userInfo.SurName.trim();
				data.name = data.name.trim();
			}
			if (localStorage.ACCOUNT) {
				data.loginName = localStorage.ACCOUNT.trim();
			}
			if (userInfo.Email) {
				data.email = userInfo.Email.trim();
			}
			if (userInfo.Mobile) {
				data.phone = userInfo.Mobile.trim();
			}

			var href = API_URL.SUPPORT;
			if (self.data.AppDetails.supportPageUrl) {
				href = self.data.AppDetails.supportPageUrl
			}
			//href += '?' + app.utils.serializeObject(data);
			window.open(href, '_blank');
		},
		clearUserInfo: function () {
			var self = this;

			var userInfo = self.methods.getFromStorage('userInfo');

			var deviceToken = localStorage.PUSH_DEVICE_TOKEN;
			var mobileToken = localStorage.PUSH_MOBILE_TOKEN;

			var notifications = self.methods.getFromStorage('notifications');
			var virtualList = self.virtualList.get('.assetList');
			var notificationsIconEl = $$('.openNotificationsPageLink i');
			var mapSettings = self.methods.getFromStorage('mapSettings');
			var otherSettings = self.methods.getFromStorage('otherSettings');

			 
	

			POSINFOASSETLIST = {};
			if (AllMarkersGroup) {
				AllMarkersGroup.clearLayers();
				if (MapTrack) {
					MapTrack.removeLayer(AllMarkersGroup);
				}
			}
			if(MapControls) {
				MapControls.hideGeofences();
			}
			
			if (virtualList) {
				virtualList.deleteAllItems();
			}

			if (notifications) {
				localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.NOTIFICATIONS", JSON.stringify(notifications));
			}
			if (mapSettings) {
				self.methods.setInStorage({ name: 'mapSettings', data: mapSettings });
			}
			if (otherSettings) {
				self.methods.setInStorage({ name: 'otherSettings', data: otherSettings });
			}
			if (deviceToken) {
				localStorage.PUSH_DEVICE_TOKEN = deviceToken;
			}
			if (mobileToken) {
				localStorage.PUSH_MOBILE_TOKEN = mobileToken;
			}

			if (UpdateAssetsPosInfoTimer) {
				clearInterval(UpdateAssetsPosInfoTimer);
			}
			if (UpdateNotificationsTimer) {
				clearInterval(UpdateNotificationsTimer);
			}

			if (notificationsIconEl && notificationsIconEl.length) {
				notificationsIconEl.empty();
			}

			var data = {
				MinorToken: userInfo.MinorToken,
				deviceToken: deviceToken,
				mobileToken: mobileToken,
			};
			// app.request.get(API_URL.LOGOUT, data, function (result, xhr, status) {
			// },
			// 	function (xhr, status) {
			// 		//app.dialog.alert('Error occured');
			// 	},
			// 	'json');
			localStorage.clear();
		},
		prelogout: function () {
			var self = this;
			
			var userInfo = self.methods.getFromStorage('userInfo');
			
			app.request.get(API_URL.LOGOUT + '?MinorToken=' + userInfo?.MinorToken + '&MajorToken=' + userInfo?.MajorToken + '&deviceToken=' + localStorage.PUSH_DEVICE_TOKEN, function (result, xhr, status) {
			 
					app.methods.logout();
			    },
			 	function (xhr, status) {
			 		//app.dialog.alert('Error occured');
					console.log('error logout')
			 	},
			 	'json');
			/*setTimeout(() => {
				location.reload();
			}, 1000)*/
		},
		logout: function () {
			var self = this;
			if (localStorage.ACCOUNT) {
				$$("input[name='username']").val(localStorage.ACCOUNT);
			}
			//console.log('here')

			//
			//app.router.navigate('/login-screen/');
			self.methods.clearUserInfo();

			if (dashboardView) {
				dashboardView.destroy();
				dashboardView = false;
				$$('.view-dashboard').empty();
			}
			self.utils.nextTick(() => {
				leftView.router.back('/panel-left/');
			}, 300);
			
			//window.location.href = window.location.pathname.split('/')[1]
			//console.log('parsedUrl', )
			//let parsedPath = window.location.pathname.split('/')[1]
			//if (parsedPath) {
			/*switch (parsedPath) {
				case 'fridgewatch':
					location.href = 'https://gps-secure.co/fridgewatch';//'http://fridgewatch.net.au/';
					break;
				default:
					self.loginScreen.open('.login-screen');
			}*/
			/*switch (parsedUrl.input) {
				case 'test.quikloc8.com':
				case 'classic.quikloc8.com':
				case 'carcitywest.quikloc8.com':
				case 'marine.quikloc8.com':
				case 'cubetrackit.quikloc8.com':
	
				case 'geelinxgps.quikloc8.com':
				case 'geelinxgps.com':
				case 'www.geelinxgps.com':
				case 'online.cubetrackit.com.au':
	
				case 'heli.gps-secure.co':
				case 'plantwach.gps-secure.co':
	
				case 'alert.gps-secure.co':
				case 'al3rt.gps-secure.co':
				case 'alertgps.gps-secure.co':
	
				case 'new.gps-secure.co':
				case 'gps-secure.co':
	
				case 'western.gps-secure.co':
				case 'cobra.boatwatch.co':
				case 'smartostrichfleet.gps-secure.co':
				case 'smartostrichfleet.com':
				case 'autoprotect.gps-secure.co':
				case 'autoprotect.live':
	
					location.href = '/';
					break;
	
				default:
					self.loginScreen.open('.login-screen');
			}*/
			//} else {
			self.loginScreen.open('.login-screen');
			//}
			self.emit('loggedOff');
			self.preloader.hide();
			self.methods.hideHelloPreloader()
			

		},
		login: function (params) {
			var self = this;
			self.methods.getPlusInfo();

			var account = $$("input[name='username']");
			var password = $$("input[name='password']");

			var data = {
				account: account.val() ? account.val() : localStorage.ACCOUNT,
				password: password.val() ? password.val() : localStorage.PASSWORD,
				appKey: localStorage.PUSH_APP_KEY,
				mobileToken: localStorage.PUSH_MOBILE_TOKEN,
				deviceToken: localStorage.PUSH_DEVICE_TOKEN,
				deviceType: localStorage.DEVICE_TYPE,
			};

			self.methods.setAccountToLocalDB(data.account)

			self.dialog.progress(LANGUAGE.COM_MSG08, !Template7.global.DEALER_PRELOADER_COLOR_CLASS ? '' : Template7.global.DEALER_PRELOADER_COLOR_CLASS);
			self.request.get(API_URL.LOGIN, data, function (result, xhr, status) {

				//console.log('login',result);
				if (result && result.MajorCode == '000') {

					if (account.val()) {
						localStorage.ACCOUNT = account.val().trim().toLowerCase();
						localStorage.PASSWORD = password.val();
					}

					password.val(null);
					//self.methods.setInStorage({name:'userInfo', data:result.Data });
					self.methods.setInStorage({
						name: 'userInfo',
						data: {
							MajorToken: result.Data.MajorToken,
							MinorToken: result.Data.MinorToken,
							UserInfo: result.Data.UserInfo
						}
					});
					self.data.CustomerType = result.Data.UserInfo.CustomerType;
					self.data.MinorToken = result.Data.MinorToken;
					self.data.MajorToken = result.Data.MajorToken;
					
					PERMISSIONS = result.Data.Permissions
					USERROLE = result.Data.UserInfo.Role;
				 
					if(USERROLE == 0 || USERROLE == 4){
						//console.log('ROLE', USERROLE);
						self.methods.logout();
						window.top.location.href = 'https://cartrack.co/loc8/' + `${parsedDealer}`; 
						//self.loginScreen.open('.login-screen');
					}
					/*~~
					self.request.post(API_URL.PRE_EDIT_CUSTOMER, {
						MajorToken: self.data.MajorToken,
						MinorToken: self.data.MinorToken,
						Code: self.data.MajorToken
					  }, function (result, xhr, status) {
						//console.log('perm', result);
						if (result) {
							//PERMISSIONS = result.ContactInfo.Permissions
							PERMISSIONS = result.Permissions
							//console.log('perm', PERMISSIONS);							
						}
					},
					function (xhr, status) {

					},
					'json');
					~~*/

		 
					 
					if (parsedUrl.sld === "quikloc8" && parsedUrl.subdomain === "test") {
						if ((result.Data.UserInfo.CustomerType === 2 || result.Data.UserInfo.CustomerType === 6)  ) {
							mainView.router.navigate('/admin/');
							app.loginScreen.close();
							app.dialog.close();

							self.methods.clearUserInfo();
							return;
						}
					} else if (result.Data.UserInfo.CustomerType === 1 || result.Data.UserInfo.CustomerType === 2) {
						let username = localStorage.ACCOUNT;
						let password = localStorage.PASSWORD;
						self.methods.clearUserInfo();
						//console.log(self.data.AppDetails, self.data.AppDetails.agentLoginUrl, `?username=${username}&password=${password}`)
						//~~window.location.href = self.data.AppDetails.agentLoginUrl + `?username=${username}&password=${password}`
						window.top.location.href = 'https://cartrack.co' + `?username=${result.Data.MajorToken}&password=${result.Data.MinorToken}&dealer=${parsedDealer}&ui=loc8`
						return;
					}

					self.methods.setInStorage({ name: 'contactList', data: result.Data.ContactList });
					//self.methods.setInStorage({name:'dashboard', data:result.Data.Dashboard });
					self.methods.setInStorage({ name: 'solutions', data: result.Data.Solutions });
					self.methods.setInStorage({ name: 'assetTypes', data: result.Data.AssetTypes });
					self.methods.setInStorage({ name: 'permissions2', data: result.Data.Permissions2 });
					if (result.Data.AlarmNames) {
						self.methods.setInStorage({ name: 'userAlarmSettings', data: result.Data.AlarmNames });
					}

					var assetListObj = self.methods.setAssetList({ list: result.Data.AssetArray });
					var otherSettings = self.methods.getFromStorage('otherSettings');

					self.methods.getAssetListPosInfo(assetListObj);
					self.methods.updateUserCredits(result.Data.UserInfo.SMSTimes);
					self.methods.setAccountSolutions(assetListObj);
					self.methods.getAlertList({ MajorToken: result.Data.MajorToken, MinorToken: result.Data.MinorToken });
					self.methods.getGeofenceList({ MajorToken: result.Data.MajorToken, MinorToken: result.Data.MinorToken });
					self.methods.getDashboardData({ MajorToken: result.Data.MajorToken, MinorToken: result.Data.MinorToken });

					if (UpdateAssetsPosInfoTimer) clearInterval(UpdateAssetsPosInfoTimer);
					UpdateAssetsPosInfoTimer = setInterval(function () {
						//console.log('here')
						self.methods.getAssetListPosInfo(assetListObj, 1);  // '1' - means update
					}, otherSettings && otherSettings.DataUpdateInterval ? parseInt(otherSettings.DataUpdateInterval) * 1000 : 30 * 1000);

					self.methods.getNewNotifications();
					if (UpdateNotificationsTimer) clearInterval(UpdateNotificationsTimer);
					UpdateNotificationsTimer = setInterval(function () {
						self.methods.getNewNotifications();
					}, 20 * 1000);

					if (params && params.page === 'dashboard'  && (USERROLE == 1 || USERROLE == 2 || USERROLE == 3 || USERROLE == 8 || USERROLE == 11)) {
						self.popup.open('.popup-fullscreen-dashboard');
					}
					self.emit('loggedIn')
					self.panel.close();
					self.loginScreen.close();
					leftView.router.back('/panel-left/');
					self.methods.hideHelloPreloader()
				} else {
					self.utils.nextFrame(() => {
						self.dialog.close();
						self.dialog.alert(LANGUAGE.LOGIN_MSG01);
						self.loginScreen.open('.login-screen');
						self.methods.hideHelloPreloader()
					});

					//app.router.navigate('/login-screen/');
				}
			},
				function (xhr, status) {
					self.utils.nextFrame(() => {
						self.dialog.close();
						//app.dialog.alert('Error occurred during get categories request!');
						self.dialog.alert('Error occured during login');
						self.loginScreen.open('.login-screen');
						self.methods.hideHelloPreloader()
					});
				},
				'json');
		},
		hideHelloPreloader: function () {
			setTimeout(function () { fadeOutnojquery(hellopreloader); }, 1000);
		},
		getNewAssetsData: function (resolve) {
			var self = this;
			self.methods.getPlusInfo();

			var data = {
				account: localStorage.ACCOUNT,
				password: localStorage.PASSWORD,
				appKey: localStorage.PUSH_APP_KEY,
				mobileToken: localStorage.PUSH_MOBILE_TOKEN,
				deviceToken: localStorage.PUSH_DEVICE_TOKEN,
				deviceType: localStorage.DEVICE_TYPE,
			};

			self.request.get(API_URL.LOGIN, data, function (result, xhr, status) {
				//console.log(result);
				if (result && result.MajorCode === '000') {
					var assetListObj = self.methods.setAssetList({ list: result.Data.AssetArray })
					var otherSettings = self.methods.getFromStorage('otherSettings');

					self.methods.setInStorage({ name: 'userInfo', data: result.Data });
					self.methods.updateUserCredits(result.Data.UserInfo.SMSTimes);
					//self.methods.setAssetList({list: result.Data.AssetArray});
					self.methods.getAssetListPosInfo(assetListObj, 1);

					if (UpdateAssetsPosInfoTimer) clearInterval(UpdateAssetsPosInfoTimer);
					UpdateAssetsPosInfoTimer = setInterval(function () {
					 
						self.methods.getAssetListPosInfo(assetListObj, 1);  // '1' - means update
					}, otherSettings && otherSettings.DataUpdateInterval ? parseInt(otherSettings.DataUpdateInterval) * 1000 : 30 * 1000);

					if (typeof resolve === "function") {
						resolve();
					}
				}
			},
				function (xhr, status) {
					console.log('Error occured doring getNewAssetsData');
					if (reject) {
						reject();
					}
				},
				'json');
		},
		reLogin: function (resolve, reject) {
			var self = this;
			self.methods.getPlusInfo();

			var data = {
				account: localStorage.ACCOUNT,
				password: localStorage.PASSWORD,
				appKey: localStorage.PUSH_APP_KEY,
				mobileToken: localStorage.PUSH_MOBILE_TOKEN,
				deviceToken: localStorage.PUSH_DEVICE_TOKEN,
				deviceType: localStorage.DEVICE_TYPE,
			};

			self.request.get(API_URL.LOGIN, data, function (result, xhr, status) {
				if (result && result.MajorCode === '000') {
					var assetListObj = self.methods.setAssetList({ list: result.Data.AssetArray })
					var otherSettings = self.methods.getFromStorage('otherSettings');

					self.methods.setInStorage({ name: 'userInfo', data: result.Data });
					self.methods.updateUserCredits(result.Data.UserInfo.SMSTimes);
					//self.methods.setAssetList({list: result.Data.AssetArray});


					if (UpdateAssetsPosInfoTimer) clearInterval(UpdateAssetsPosInfoTimer);
					UpdateAssetsPosInfoTimer = setInterval(function () {
						self.methods.resetAssetListPosInfo(assetListObj);
					}, otherSettings && otherSettings.DataUpdateInterval ? parseInt(otherSettings.DataUpdateInterval) * 1000 : 30 * 1000);
					self.methods.resetAssetListPosInfo(assetListObj);

					if (typeof resolve === "function") {
						resolve();
					}
				}
			},
				function (xhr, status) {
					console.log('Error occured doring getNewAssetsData');
					if (typeof reject === "function") {
						reject();
					}
				},
				'json');
		},
		setAssetList: function (params = {}) {
			
			var self = this;
			//console.log('userInfo',USERROLE)
			var ret = '';
			//console.log(params.list)
			if (params.list && params.list.length) {
				var ary = {};
				for (var i = 0; i < params.list.length; i++) {
					var index = 0;
					if(params.list[i][48] === 'False' && USERROLE != 2 || USERROLE == 2){
						//console.log('SEEEE')
					ary[params.list[i][1]] = {
						Id: params.list[i][index++],
						IMEI: params.list[i][index++],
						Name: params.list[i][index++],
						TagName: params.list[i][index++],
						Icon: params.list[i][index++],
						Unit: params.list[i][index++],
						InitMileage: params.list[i][index++],
						InitAcconHours: params.list[i][index++],
						State: params.list[i][index++],
						ActivateDate: params.list[i][index++],
						PayPlanName: params.list[i][index++],
						PRDTName: params.list[i][index++],
						PRDTFeatures: params.list[i][index++],
						PRDTAlerts: params.list[i][index++],
						Describe1: params.list[i][index++],
						Describe2: params.list[i][index++],
						Describe3: params.list[i][index++],
						Describe4: params.list[i][index++],
						Describe5: params.list[i][index++],
						_FIELD_FLOAT1: params.list[i][index++],
						_FIELD_FLOAT2: params.list[i][index++],
						_FIELD_FLOAT7: params.list[i][index++],
						Describe7: params.list[i][index++],
						AlarmOptions: params.list[i][index++],
						StatusNew: params.list[i][index++],
						_FIELD_FLOAT8: params.list[i][index++],
						IMSI: params.list[i][index++],
						_FIELD_INT2: params.list[i][index++],
						GroupCode: params.list[i][index++],
						SolutionType: params.list[i][index++],
						Registration: params.list[i][index++],
						StockNumber: params.list[i][index++],
						MaxSpeed: params.list[i][index++],
						MaxSpeedAlertMode: params.list[i][index++],
						DaysInInventory: moment.utc().diff(moment.utc(params.list[i][index], window.COM_TIMEFORMAT), 'days'),
						StorageTime: params.list[i][index++],
						ActivationTime: params.list[i][index++],
						BusinessExpense: params.list[i][index++],
						FuelEconomy: params.list[i][index++],
						EngineCapacity: params.list[i][index++],
						OffroadTaxCredit: params.list[i][index++],
						AssetType: params.list[i][index++],
						AlarmOptions2: params.list[i][index++],
						DriverCode: params.list[i][index++],
						RoadSpeed: params.list[i][index++],
						LBSWIFI: params.list[i][index++],
						STATICDRIFT: params.list[i][index++],
						Input1Name_: params.list[i][index++],
						Input2Name_: params.list[i][index++],
						isShared: (params.list[i][index++].toLowerCase() === "true"),
						SuspendDate: params.list[i][index++],
						undefined1: params.list[i][index++],
						undefined2: params.list[i][index++],
						undefined3: params.list[i][index++],
						Input1Type: params.list[i][index++], //ignore
						Input1Name: params.list[i][index++],
						Input1Mask: params.list[i][index++], //ignore
						Input1Icon: params.list[i][index++],
						Input2Type: params.list[i][index++], //ignore
						Input2Name: params.list[i][index++],
						Input2Mask: params.list[i][index++], //ignore
						Input2Icon: params.list[i][index++],
						Input3Type: params.list[i][index++], //ignore
						Input3Name: params.list[i][index++],
						Input3Mask: params.list[i][index++], //ignore
						Input3Icon: params.list[i][index++],
						Input4Type: params.list[i][index++], //ignore
						Input4Name: params.list[i][index++],
						Input4Mask: params.list[i][index++], //ignore
						Input4Icon: params.list[i][index++],
						Output1Type: params.list[i][index++], //ignore
						Output1Name: params.list[i][index++],
						Output1Mask: params.list[i][index++], //ignore
						Output1Icon: params.list[i][index++],
						Output2Type: params.list[i][index++], //ignore
						Output2Name: params.list[i][index++],
						Output2Mask: params.list[i][index++], //ignore
						Output2Icon: params.list[i][index++],
						SubscriptionId: params.list[i][index++],
						undefined4: params.list[i][index++],
						LicenceDisk: params.list[i][index++],
						DiskExpiryDate: params.list[i][index++],
						undefined5: params.list[i][index++],
						undefined6: params.list[i][index++],
						undefined7: params.list[i][index++],
						iButtonFlag: params.list[i][index++],
					};
					/*if (POSINFOASSETLIST && POSINFOASSETLIST[params[i][1]]) {
								  POSINFOASSETLIST[params[i][1]].StatusNew =  ary[params[i][1]].StatusNew;
							  }  */
					}
				}
				ret = ary;
				localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.ASSETLIST", JSON.stringify(ary));	//~~~			
				self.methods.setToLocalDB("COM.QUIKTRAK.QUIKLOC8.ASSETLIST", JSON.stringify(ary));
				/*$.ajax({
							type: "POST",								
							url: "../resources/php/set.php", 
							dataType: 'json',
							data: JSON.stringify({storage_name: "COM.QUIKTRAK.QUIKLOC8.ASSETLIST", storage_account: localStorage.ACCOUNT, storage_data: ary}), //JSON.stringify({storage_name, storage_data: storage_data, storage_account: localStorage.ACCOUNT}),
							async: true, 
							cache: false,
							beforeSend: function(){
								
							},	
							success: function(data){
								//console.log('set data to ' + storage_name)
							},
							error: function(XMLHttpRequest, textStatus, errorThrown){
								console.log(XMLHttpRequest);
								console.log(textStatus);
								console.log(errorThrown);								
							}													
						});*/

			} else if (params.device) {
				var list = self.methods.getFromStorage('assetList');

				if (POSINFOASSETLIST[params.device.IMEI]) {
					POSINFOASSETLIST[params.device.IMEI].Name = list[params.device.IMEI].Name = params.device.name;
					POSINFOASSETLIST[params.device.IMEI].TagName = list[params.device.IMEI].TagName = params.device.tag;
					POSINFOASSETLIST[params.device.IMEI].Registration = list[params.device.IMEI].Registration = params.device.registration;
					POSINFOASSETLIST[params.device.IMEI].Unit = list[params.device.IMEI].Unit = params.device.speedUnit;
					POSINFOASSETLIST[params.device.IMEI].InitMileage = list[params.device.IMEI].InitMileage = params.device.initMileage;
					POSINFOASSETLIST[params.device.IMEI].InitAcconHours = list[params.device.IMEI].InitAcconHours = params.device.initAccHours;
					POSINFOASSETLIST[params.device.IMEI].Describe1 = list[params.device.IMEI].Describe1 = params.device.attr1;
					POSINFOASSETLIST[params.device.IMEI].Describe2 = list[params.device.IMEI].Describe2 = params.device.attr2;
					POSINFOASSETLIST[params.device.IMEI].Describe3 = list[params.device.IMEI].Describe3 = params.device.attr3;
					POSINFOASSETLIST[params.device.IMEI].Describe4 = list[params.device.IMEI].Describe4 = params.device.attr4;
					POSINFOASSETLIST[params.device.IMEI].GroupCode = list[params.device.IMEI].GroupCode = params.device.groupCode;
					POSINFOASSETLIST[params.device.IMEI].DriverCode = list[params.device.IMEI].DriverCode = params.device.DriverCode;
					POSINFOASSETLIST[params.device.IMEI].RoadSpeed = list[params.device.IMEI].RoadSpeed = params.device.RoadSpeed;
					POSINFOASSETLIST[params.device.IMEI].LBSWIFI = list[params.device.IMEI].LBSWIFI = params.device.LBSWIFI;
					POSINFOASSETLIST[params.device.IMEI].STATICDRIFT = list[params.device.IMEI].STATICDRIFT = params.device.STATICDRIFT;
					POSINFOASSETLIST[params.device.IMEI].Input1Name = list[params.device.IMEI].Input1Name = params.device.Input1Name;
					POSINFOASSETLIST[params.device.IMEI].Input2Name = list[params.device.IMEI].Input2Name = params.device.Input2Name;
					POSINFOASSETLIST[params.device.IMEI].Input3Name = list[params.device.IMEI].Input3Name = params.device.Input3Name;
					POSINFOASSETLIST[params.device.IMEI].Input4Name = list[params.device.IMEI].Input4Name = params.device.Input4Name;
					POSINFOASSETLIST[params.device.IMEI].Output1Name = list[params.device.IMEI].Output1Name = params.device.Output1Name;
					POSINFOASSETLIST[params.device.IMEI].Output2Name = list[params.device.IMEI].Output2Name = params.device.Output2Name;

					if (params.device.stockNumber) {
						POSINFOASSETLIST[params.device.IMEI].StockNumber = list[params.device.IMEI].StockNumber = params.device.stockNumber;
					}
					if (params.device.icon) {
						POSINFOASSETLIST[params.device.IMEI].Icon = list[params.device.IMEI].Icon = params.device.icon + '?' + new Date().getTime();
					}
					if (params.device.MaxSpeed) {
						POSINFOASSETLIST[params.device.IMEI].MaxSpeed = list[params.device.IMEI].MaxSpeed = params.device.MaxSpeed;
					}
					if (params.device.BusinessExpense) {
						POSINFOASSETLIST[params.device.IMEI].BusinessExpense = list[params.device.IMEI].BusinessExpense = params.device.BusinessExpense;
					}
					if (params.device.FuelEconomy) {
						POSINFOASSETLIST[params.device.IMEI].FuelEconomy = list[params.device.IMEI].FuelEconomy = params.device.FuelEconomy;
					}
					if (params.device.EngineCapacity) {
						POSINFOASSETLIST[params.device.IMEI].EngineCapacity = list[params.device.IMEI].EngineCapacity = params.device.EngineCapacity;
					}
					if (params.device.OffroadTaxCredit) {
						POSINFOASSETLIST[params.device.IMEI].OffroadTaxCredit = list[params.device.IMEI].OffroadTaxCredit = params.device.OffroadTaxCredit;
					}
					if (params.device.AssetType) {
						POSINFOASSETLIST[params.device.IMEI].AssetType = list[params.device.IMEI].AssetType = params.device.AssetType;
					}



				} else {
					list[params.device.IMEI].Name = params.device.name;
					list[params.device.IMEI].TagName = params.device.tag;
					list[params.device.IMEI].Registration = params.device.registration;
					list[params.device.IMEI].Unit = params.device.speedUnit;
					list[params.device.IMEI].InitMileage = params.device.initMileage;
					list[params.device.IMEI].InitAcconHours = params.device.initAccHours;
					list[params.device.IMEI].Describe1 = params.device.attr1;
					list[params.device.IMEI].Describe2 = params.device.attr2;
					list[params.device.IMEI].Describe3 = params.device.attr3;
					list[params.device.IMEI].Describe4 = params.device.attr4;
					list[params.device.IMEI].GroupCode = params.device.groupCode;
					list[params.device.IMEI].DriverCode = params.device.DriverCode;
					list[params.device.IMEI].RoadSpeed = params.device.RoadSpeed;
					list[params.device.IMEI].LBSWIFI = params.device.LBSWIFI;
					list[params.device.IMEI].STATICDRIFT = params.device.STATICDRIFT;
					list[params.device.IMEI].Input1Name = params.device.Input1Name;
					list[params.device.IMEI].Input2Name = params.device.Input2Name;
					list[params.device.IMEI].Input3Name = params.device.Input3Name;
					list[params.device.IMEI].Input4Name = params.device.Input4Name;
					list[params.device.IMEI].Output1Name = params.device.Output1Name;
					list[params.device.IMEI].Output2Name = params.device.Output2Name;

					if (params.device.stockNumber) {
						list[params.device.IMEI].StockNumber = params.device.stockNumber;
					}
					if (params.device.icon) {
						list[params.device.IMEI].Icon = params.device.icon + '?' + new Date().getTime();
					}
					if (params.device.MaxSpeed) {
						list[params.device.IMEI].MaxSpeed = params.device.MaxSpeed;
					}
					if (params.device.BusinessExpense) {
						list[params.device.IMEI].BusinessExpense = params.device.BusinessExpense;
					}
					if (params.device.FuelEconomy) {
						list[params.device.IMEI].FuelEconomy = params.device.FuelEconomy;
					}
					if (params.device.EngineCapacity) {
						list[params.device.IMEI].EngineCapacity = params.device.EngineCapacity;
					}
					if (params.device.OffroadTaxCredit) {
						list[params.device.IMEI].OffroadTaxCredit = params.device.OffroadTaxCredit;
					}
					if (params.device.AssetType) {
						list[params.device.IMEI].AssetType = params.device.AssetType;
					}

				}

				localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.ASSETLIST", JSON.stringify(list));//~~~

				self.methods.setToLocalDB("COM.QUIKTRAK.QUIKLOC8.ASSETLIST", JSON.stringify(list));
				/*}else if(params.devices){
						var list = self.methods.getFromStorage('assetList');
		
						for (var i = params.devices.length - 1; i >= 0; i--) {
							if (params.devices[i].IMEI && params.devices[i].Props) {
								let keys = Object.keys(params.devices[i].Props);
								for (const key of keys) {
									if (POSINFOASSETLIST[params.devices[i].IMEI][key]) {
										POSINFOASSETLIST[params.devices[i].IMEI][key] = list[params.devices[i].IMEI][key] = params.devices[i].Props[key];
									}else{
										list[params.devices[i].IMEI][key] = params.devices[i].Props[key];
									}
		
								}
							}
						}
		
						localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.ASSETLIST", JSON.stringify(list));*/

			} else if (params.objects) {
				localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.ASSETLIST", JSON.stringify(params.objects));//~~~

				self.methods.setToLocalDB("COM.QUIKTRAK.QUIKLOC8.ASSETLIST", JSON.stringify(params.objects));
			}

			//console.log(ary);
			return ret;
		},
		setAccountSolutions: function (assetList) {
			let solutions = [];
			const keys = Object.keys(assetList);
			for (const key of keys) {
				if (assetList[key].SolutionType) {
					let solution = assetList[key].SolutionType.toLowerCase();
					let index = solutions.indexOf(solution);
					if (index == -1 && solution.toLowerCase() !== 'deactivate') {
						solutions.push(solution);
					}
				}
			}
			solutions.sort();
			solutions.reverse();
			this.data.AccountSolutionArray = solutions;
		},
		getGeofenceName: function (code, geofenceList) {
			let ret = '';
			if (code && !app.methods.isObjEmpty(geofenceList)) {
				let index = geofenceList.findIndex(obj => obj.Code == code);
				if (index != -1) {
					ret = geofenceList[index].Name;
				}
			}
			return ret
		},
		getAssetListPosInfo: function (listObj, update) {
			var self = this;
			var userInfo = self.methods.getFromStorage('userInfo');

			var codes = '';
			$.each(listObj, function (index, val) {
				codes += val.Id + ',';
			});
			if (codes) {
				codes = codes.slice(0, -1);
			}

			var url = self.utils.serializeObject({ MinorToken: userInfo.MinorToken, MajorToken: userInfo.MajorToken });

			url = API_URL.GET_ALL_POSITIONS + '?' + url;

			var data = {
				codes: codes,
			};

			//app.dialog.progress();
			self.request.post(url, data, function (result, xhr, status) {
				//console.log(result);
				if (result.MajorCode == '000') {
					var data = result.Data;
					if (result.Data) {
						var posData = '';
						var imei = '';
						var protocolClass = '';
						var deviceInfo = '';

						if (!update) {
							for (var i = result.Data.length - 1; i >= 0; i--) {
								posData = result.Data[i];
								imei = posData[1];
								protocolClass = posData[2].replace(/\s/g, '');
								deviceInfo = listObj[imei];
								//!self.methods.isObjEmpty(POSINFOASSETLIST[imei])
								if (!self.methods.isObjEmpty(deviceInfo) && deviceInfo.IMEI === imei) {

									POSINFOASSETLIST[imei] = Protocol.ClassManager.get(protocolClass, deviceInfo);
									POSINFOASSETLIST[imei].initPosInfo(posData);
								}
							}
						} else {
							for (let i = data.length - 1; i >= 0; i--) {
								posData = data[i];
								imei = posData[1];

								if (!self.methods.isObjEmpty(POSINFOASSETLIST[imei]) && !POSINFOASSETLIST[imei].posInfo.positionTime || !self.methods.isObjEmpty(POSINFOASSETLIST[imei]) && posData[5] >= POSINFOASSETLIST[imei].posInfo.positionTime._i) {
									POSINFOASSETLIST[imei].initPosInfo(posData);
									//self.utils.nextFrame(()=>{
									self.methods.updateMarker(imei);
									self.methods.updateAssetListStat(imei);
									if (self.data.BottomWidgetAssetImei === imei) {
										self.emit('bottomWidgetShowAssetDetails', imei)
									}
									//});
								}
							}
							self.emit('assetPosInfoUpdateReceived', POSINFOASSETLIST)
						}
					}
				}
				if (!update) {
					//self.methods.initAssetList();

					self.methods.setAllMarkers();

					self.methods.initGroupAssetList({
						ShowDashboard: self.data.CustomerType === 2 || self.data.CustomerType === 6,
					});

					self.utils.nextFrame(() => {
						self.dialog.close();
					});

				}

			},
				function (xhr, status) {

				},
				'json');
		},
		resetAssetListPosInfo: function (listObj) {
			var self = this;
			var userInfo = self.methods.getFromStorage('userInfo');

			var codes = '';
			$.each(listObj, function (index, val) {
				codes += val.Id + ',';
			});
			if (codes) {
				codes = codes.slice(0, -1);
			}

			var url = self.utils.serializeObject({ MinorToken: userInfo.MinorToken, MajorToken: userInfo.MajorToken });

			url = API_URL.GET_ALL_POSITIONS + '?' + url;

			var data = {
				codes: codes,
			};

			//app.dialog.progress();
			self.request.post(url, data, function (result, xhr, status) {
				//console.log(result);
				if (result.MajorCode == '000') {
					var data = result.Data;
					if (result.Data) {
						var posData = '';
						var imei = '';
						var protocolClass = '';
						var deviceInfo = '';


						for (var i = result.Data.length - 1; i >= 0; i--) {
							posData = result.Data[i];
							imei = posData[1];
							protocolClass = posData[2];
							deviceInfo = listObj[imei];
							//!self.methods.isObjEmpty(POSINFOASSETLIST[imei])
							if (!self.methods.isObjEmpty(deviceInfo) && deviceInfo.IMEI === imei) {
								POSINFOASSETLIST[imei] = Protocol.ClassManager.get(protocolClass, deviceInfo);
								POSINFOASSETLIST[imei].initPosInfo(posData);
							}
						}

					}
				}

				if (AllMarkersGroup) {
					AllMarkersGroup.clearLayers();
					if (MapTrack) {
						MapTrack.removeLayer(AllMarkersGroup);
					}
				}
				self.methods.setAllMarkers();

			},
				function (xhr, status) {

				},
				'json');
		},

		initGroupAssetList: function (params = {}) {
			var self = this;

			var userInfo = self.methods.getFromStorage('userInfo');
			//GET_GROUP_LIST
			var data = {
				MinorToken: userInfo.MinorToken,
				MajorToken: userInfo.MajorToken,
			};

			self.preloader.show();
			self.request.post(API_URL.GET_GROUP_LIST, data, function (result, xhr, status) {
				self.preloader.hide();
				//console.log(result);
				if (result && result.MajorCode == '000') {
					if (result.Data) {
						var groupList = result.Data;
						var assetList = self.methods.getFromStorage('assetList');
						var newAssetList = [];
						var keys = Object.keys(assetList);
						$.each(keys, function (index, value) {
							newAssetList.push(assetList[value]);
						});
						newAssetList.sort(function (a, b) {
							if (a.Name < b.Name) return -1;
							if (a.Name > b.Name) return 1;
							return 0;
						});

						groupList.push({
							Name: LANGUAGE.ASSET_GROUPS_MSG11, //no group group
							Code: '000000',
						});

						$.each(newAssetList, function (key, val) {
							var group = false;
							if (val.GroupCode) {
								group = self.methods.findObjectByKey(groupList, 'Code', val.GroupCode);
							}

							if (!group) {
								group = self.methods.findObjectByKey(groupList, 'Code', '000000');
							}

							if (group && group.Assets) {
								group.Assets.push(val);
							} else if (group) {
								group.Assets = [val];
							}
						});

						groupList.sort(function (a, b) {
							if (a.Name < b.Name) return -1;
							if (a.Name > b.Name) return 1;
							return 0;
						});

						/*move not assigned asset to the bottom*/
						groupList.push(groupList.splice(groupList.findIndex(x => x.Code == '000000'), 1)[0]);

						self.methods.setInStorage({ name: 'groupList', data: groupList });

						groupList = self.methods.sortListByState(groupList, 'state');

						var virtualList = self.virtualList.get('.assetList');
						if (virtualList && virtualList.items && virtualList.items.length) {
							virtualList.replaceAllItems(groupList);
						} else {
							virtualList.appendItems(groupList);
						}

						if (params.ShowDashboard  && (USERROLE == 1 || USERROLE == 2 || USERROLE == 3 || USERROLE == 8 || USERROLE == 11)) {
							dashboardPopup.open();
						}
						/*if (self.data.CustomerType == 2 || self.data.CustomerType == 6) {
										  //if Agent or Dealer
										  dashboardPopup.open();
									  }     */
					}


				} else if (result && result.MajorCode == '100' && result.MinorCode == '1003') {
					/* self.$app.utils.nextTick(function() {
									leftView.router.back();
								},500);    */
					self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
				} else {
					/*self.$app.utils.nextTick(function() {
									leftView.router.back();
								},500);    */
					self.dialog.alert('Something wrong at initGroupAssetList');
				}

			},
				function (xhr, status) {
					self.preloader.hide();
					self.dialog.alert('Error occured at getGroupList');
				},
				'json');
		},
		/*initAssetList: function() {
				var self = this;
				var assetList = self.methods.getFromStorage('assetList');
		
				var newAssetlist = [];
				var keys = Object.keys(assetList);
				for (var i = 0, len = keys.length; i < len; i++) {
				  newAssetlist.push(assetList[keys[i]]);
				}
		
				newAssetlist.sort(function(a,b){
					if(a.Name < b.Name) return -1;
					if(a.Name > b.Name) return 1;
					return 0;
				});
		
				//returnToIndex();
		
				var virtualAssetList = self.virtualList.get('.assetList');
				if (virtualAssetList && virtualAssetList.items && virtualAssetList.items.length) {
					virtualAssetList.replaceAllItems(newAssetlist);
				}else{
					virtualAssetList.appendItems(newAssetlist);
				}
			},*/
		setAllMarkers: function () {
			var self = this;
			var assetList = self.methods.getFromStorage('assetList');
			AllMarkersGroup = L.markerClusterGroup({ 'maxClusterRadius': 35 });





			if (assetList) {
				var point = '';
				var markerData = '';

				$.each(assetList, function (key, value) {
					point = '';
					markerData = '';
					var asset = POSINFOASSETLIST[value.IMEI];
					var assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(asset);
					
						if(POSINFOASSETLIST[key].posInfo.lat == 0 && POSINFOASSETLIST[key].posInfo.lng == 0){
							POSINFOASSETLIST[key].posInfo.lat = '-26.180355';
							POSINFOASSETLIST[key].posInfo.lng = '28.21715';
						}
						
					if (POSINFOASSETLIST[key] && POSINFOASSETLIST[key].posInfo && parseFloat(POSINFOASSETLIST[key].posInfo.lat) !== 0 && parseFloat(POSINFOASSETLIST[key].posInfo.lng) !== 0) {
						var dynamicIcon = null;

						var rotationOptions = 0





						let timeInactive = POSINFOASSETLIST[key].posInfo.positionTime && (+moment.duration(Protocol.Helper.getDifferenceBTtwoDates(POSINFOASSETLIST[key].posInfo.positionTime, moment()), "milliseconds")) > 86400000

				 


						if (POSINFOASSETLIST[key].posInfo.speed > 20 && assetFeaturesStatus.acc && assetFeaturesStatus.acc.value === "ON") {
							dynamicIcon = Protocol.MarkerIcon[11]
							rotationOptions = +POSINFOASSETLIST[key].posInfo.direct
						}
						else if (POSINFOASSETLIST[key].posInfo.speed == 0 && assetFeaturesStatus.acc && assetFeaturesStatus.acc.value === "OFF" && timeInactive) {
							dynamicIcon = Protocol.MarkerIcon[0]
						} else if (POSINFOASSETLIST[key].posInfo.speed == 0 && assetFeaturesStatus.acc && assetFeaturesStatus.acc.value === "ON") {
							dynamicIcon = Protocol.MarkerIcon[14]
							
						} else if (POSINFOASSETLIST[key].posInfo.speed == 0 && assetFeaturesStatus.acc && assetFeaturesStatus.acc.value === "OFF") {
							dynamicIcon = Protocol.MarkerIcon[2]
						} else {
							dynamicIcon = Protocol.MarkerIcon[2]
						}

						
						point = L.marker([POSINFOASSETLIST[key].posInfo.lat, POSINFOASSETLIST[key].posInfo.lng],
							{ icon: !self.data.AppDetails.customMapMarker ? dynamicIcon : self.data.AppDetails.customMapMarker, rotationAngle: rotationOptions });

						markerData = self.methods.getMarkerDataTable(POSINFOASSETLIST[key]);
						point
							.bindPopup(markerData, { maxWidth: self.data.MaxMapPopupWidth, closeButton: false })
							.on('popupopen', function (e) {
								if (!POSINFOASSETLIST[key].posInfo.customAddress) {
									Protocol.Helper.getAddressByGeocoder({ lat: POSINFOASSETLIST[key].posInfo.lat, lng: POSINFOASSETLIST[key].posInfo.lng }, function (address) {
										POSINFOASSETLIST[key].posInfo.customAddress = address;
										markerData = self.methods.getMarkerDataTable(POSINFOASSETLIST[key]);
										e.target.setPopupContent(markerData);
										e.popup.update();
									});
								}
							});
						if (app.device.desktop) {
							point.bindTooltip(POSINFOASSETLIST[key].Name, { permanent: false, direction: 'right' });
						}
						point._custom_asset_imei = key;

						point.addTo(AllMarkersGroup);
						POSINFOASSETLIST[key].markerId = AllMarkersGroup.getLayerId(point);
						console.log('init',POSINFOASSETLIST[key].markerId)
					}
				});

				if (AllMarkersGroup.getBounds().isValid()) {
					/*console.log(AllMarkersGroup.getBounds().isValid());*/
					MapTrack.fitBounds(AllMarkersGroup.getBounds(), { padding: [16, 16], maxZoom: 13 });
					AllMarkersGroup.addTo(MapTrack);
				}

			}
		},
		updateMarker: function (imei) {
			var self = this;
			if(POSINFOASSETLIST[imei].posInfo.lat == 0 && POSINFOASSETLIST[imei].posInfo.lng == 0){
				POSINFOASSETLIST[imei].posInfo.lat = '-26.180355';
				POSINFOASSETLIST[imei].posInfo.lng = '28.21715';
			}
						
			console.log('update')
			if (POSINFOASSETLIST[imei] && POSINFOASSETLIST[imei].posInfo && POSINFOASSETLIST[imei].posInfo.lat !== 0 && POSINFOASSETLIST[imei].posInfo.lng !== 0) {
				var markerData = self.methods.getMarkerDataTable(POSINFOASSETLIST[imei]);
				var point = AllMarkersGroup.getLayer(POSINFOASSETLIST[imei].markerId);
				//console.log(point)
				if (point) {
					point.setLatLng([POSINFOASSETLIST[imei].posInfo.lat, POSINFOASSETLIST[imei].posInfo.lng]).setPopupContent(markerData);
					var popup = point.getPopup();

					if (popup.isOpen()) {
						popup.update();

						Protocol.Helper.getAddressByGeocoder({ lat: POSINFOASSETLIST[imei].posInfo.lat, lng: POSINFOASSETLIST[imei].posInfo.lng }, function (address) {
							POSINFOASSETLIST[imei].posInfo.customAddress = address;
							if (popup.isOpen()) {
								markerData = self.methods.getMarkerDataTable(POSINFOASSETLIST[imei]);
								point.setPopupContent(markerData);
								popup.update();
							}
						});
					}
				}


			}
		},

		updateAssetListStat: function (imei) {
			var assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(POSINFOASSETLIST[imei]);
			if (assetFeaturesStatus.GSM) {
				state = $$("[data-id = 'signal-state" + imei + "']");
				state.removeClass('state-0 state-1 state-2 state-3');
				state.addClass(assetFeaturesStatus.GSM.state);
			}
			if (assetFeaturesStatus.GPS) {
				state = $$("[data-id = 'satellite-state" + imei + "']");
				state.removeClass('state-0 state-1 state-2 state-3');
				state.addClass(assetFeaturesStatus.GPS.state);
			}
			if (assetFeaturesStatus.geolock) {
				state = $$("[data-id = 'geolock-state" + imei + "']");
				state.removeClass('state-0 state-1 state-2 state-3');
				state.addClass(assetFeaturesStatus.geolock.state);
			}
			if (assetFeaturesStatus.immob) {
				state = $$("[data-id = 'immob-state" + imei + "']");
				state.removeClass('state-0 state-1 state-2 state-3');
				state.addClass(assetFeaturesStatus.immob.state);
			}
			if (assetFeaturesStatus.status) {
				state = $$("[data-id = 'status-state" + imei + "']");
				state.removeClass('state-0 state-1 state-2 state-3');
				state.addClass(assetFeaturesStatus.status.state);
				state.attr('title', assetFeaturesStatus.status.value);
				/*value = $$("[data-id = 'status-value"+imei+"']");
						value.html(assetFeaturesStatus.status.value); */
			}

			if (assetFeaturesStatus.speed) {
				value = $$("[data-id = 'speed-value" + imei + "']");
				value.html(assetFeaturesStatus.speed.value);
			}
			if (assetFeaturesStatus.temperature) {
				value = $$("[data-id = 'temperature-value" + imei + "']");
				value.html(assetFeaturesStatus.temperature.value);
			}
			if (assetFeaturesStatus.fuel) {
				value = $$("[data-id = 'fuel-value" + imei + "']");
				value.html(assetFeaturesStatus.fuel.value);
			}
			if (assetFeaturesStatus.voltage) {
				value = $$("[data-id = 'voltage-value" + imei + "']");
				value.html(assetFeaturesStatus.voltage.value);
			}
			if (assetFeaturesStatus.battery) {
				value = $$("[data-id = 'battery-value" + imei + "']");
				value.html(assetFeaturesStatus.battery.value);
			}
			if (assetFeaturesStatus.acc) {
				value = $$("[data-id = 'acc-value" + imei + "']");
				value.html(assetFeaturesStatus.acc.value);
			}
		},
		getTrackingIntervalDetailByCountyCode: function (countryCode) {
			var ret = {
				Value: 0,
				Cost: 0,
				PayLink: '',
				PayPlanCode: '',
				IntervalDisplayed: Protocol.TrackingInterval[0].intervalDisplayed,
			};
			switch (countryCode) {
				case 'AUS':
					ret.Cost = Protocol.TrackingInterval[0][1][countryCode].cost;
					ret.PayLink = Protocol.TrackingInterval[0][1][countryCode].button;
					ret.PayPlanCode = Protocol.TrackingInterval[0][1][countryCode].payPlanCode;
					break;
			}
			return ret;
		},
		getUpgradeToLiveByCode: function (code = 30, imei) {
			var self = this;
			var upgradeIndex = Protocol.UpgradeToLive.findIndex(el => el.code == code)
			var findCode = code
			if (upgradeIndex == -1) {
				findCode = 30
			}

			var upgrade = Protocol.UpgradeToLive.find(el => el.code == findCode)

			var url = upgrade?.url + '?ServiceProfile=5f87b4fc-d25b-4&imeis=' + imei + '&DealerToken=' + self.data.MajorToken;
			return url;
		},
		getPOIList: function (callback) {
			let self = this;
 
			self.request.post(API_URL.GET_POI_LIST, {MajorToken: self.data.MajorToken, MinorToken: self.data.MinorToken }, function (result, xhr, status) {
				if (result && result.MajorCode == '000') {
					if (result.Data) {
						self.methods.setInStorage({ name: 'POIList', data: result.Data });;
					}
				} else {
					self.dialog.alert('Something wrong');
				}
			},
				function (xhr, status) {
					// self.$app.preloader.hide();
					self.dialog.alert('Error occured at Get POI List ');
				},
				'json');
	 

		},
		getAlertList: function (data) {
			var self = this;
			app.request.post(API_URL.GET_REPORT_ALERTLIST, data, function (result, xhr, status) {
				if (result.MajorCode == '000') {
					if (result.Data && result.Data.length) {
						self.methods.setInStorage({ name: 'alertList', data: result.Data });
					}
				}
			},
				function (xhr, status) {
					//app.dialog.alert('Error occured at Alert List ');
				},
				'json');
		},
		getGeofenceList: function (data) {
			var self = this;

			app.request.post(API_URL.GET_GEOFENCE_LIST, data, function (result, xhr, status) {
				if (result.MajorCode == '000') {
					if (result.Data && !self.methods.isObjEmpty(result.Data)) {
						self.methods.setInStorage({ name: 'geofenceList', data: result.Data });

						var mapSettingsObg = self.methods.getFromStorage('mapSettings');
						mapSettingsObg && mapSettingsObg.showGeofences ? MapControls.showGeofences() : '';
					}
				}
			},
				function (xhr, status) {
					// app.dialog.alert('Error occured at Geofence List ');
				},
				'json');
		},
		getDashboardData: function (data) {
			var self = this;

			self.request.post(API_URL.GET_DASHBOARD_DATA, data, function (result, xhr, status) {
				if (result.MajorCode == '000') {
					if (result.Data && !self.methods.isObjEmpty(result.Data)) {
						self.methods.setInStorage({ name: 'dashboard', data: result.Data });
					}
				}
			},
				function (xhr, status) {
					// app.dialog.alert('Error occured at Geofence List ');
				},
				'json');
		},
		getMySharedAssetList: function () {
			let self = this;
			return new Promise((resolve, reject) => {
				self.request.post(API_URL.GET_MY_SHARED_ASSET_LIST, { MajorToken: self.data.MajorToken, MinorToken: self.data.MinorToken },
					function (result) {
						if (result.MajorCode === '000') {

							if (result.Data?.length) {
								result.Data.forEach(itm => {
									itm.Name = POSINFOASSETLIST[itm.IMEI]?.Name || itm.IMEI
									itm.CreateTimeLocal = moment(itm.CreateTime).add(self.data.UTCOFFSET, 'minutes').format(window.COM_TIMEFORMAT);
									itm.EndTimeLocal = moment(itm.EndTime).add(self.data.UTCOFFSET, 'minutes').format(window.COM_TIMEFORMAT);
								})
								result.Data.sort(function (a, b) {
									if (a.Name < b.Name) return -1;
									if (a.Name > b.Name) return 1;
									return 0;
								});
							}
							resolve(result.Data)
						} else {
							self.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}`);
							resolve([])
						}
					},
					function (xhr, status) {
						console.log(xhr);
						console.log(status);

					},
					'json');
			})
		},
		getSubscribedAssetList: function () {
			let self = this;
			return new Promise((resolve, reject) => {
				self.request.post(API_URL.GET_SUBSCRIBED_ASSET_LIST, { MajorToken: self.data.MajorToken, MinorToken: self.data.MinorToken },
					function (result) {
						if (result.MajorCode === '000') {
							//self.methods.setInStorage({name: 'geofenceList', data: result.Data});
							if (result.Data?.length) {
								result.Data.sort(function (a, b) {
									if (a.Name < b.Name) return -1;
									if (a.Name > b.Name) return 1;
									return 0;
								});
							}
							resolve(result.Data)
						} else {
							self.dialog.alert(LANGUAGE.PROMPT_MSG023 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}`);
							resolve([])
						}
					},
					function (xhr, status) {
						console.log(xhr);
						console.log(status);

					},
					'json');
			})
		},
		getNewNotifications: function (params) {
			var self = this;

			var userInfo = self.methods.getFromStorage('userInfo');
			var MinorToken = !userInfo ? '' : userInfo.MinorToken;
			var deviceToken = !localStorage.PUSH_DEVICE_TOKEN ? '' : localStorage.PUSH_DEVICE_TOKEN;

			if (MinorToken && deviceToken) {
				var data = {
					MinorToken: MinorToken,
					deviceToken: deviceToken,
				};

				if (params && params.showLoader === true) {
					app.preloader.show();
				}
				app.request.get(API_URL.GET_NEW_NOTIFICATIONS, data, function (result, xhr, status) {
					if (params && params.showLoader === true) {
						app.preloader.hide();
					}
					if (params && params.ptr === true) {
						app.ptr.get('.ptr-content-notifications').done();
					}

					//console.log(result);
					if (result && result.MajorCode == '000') {
						var data = result.Data;

						if (Array.isArray(data) && data.length > 0) {
							self.methods.setNotificationList(result.Data);
						}

						if (params && params.loadPageNotification === true) {
							var user = localStorage.ACCOUNT;
							var notList = self.methods.getFromStorage('notifications');
							if (notList && notList[user] && notList[user].length > 0 || Array.isArray(data) && data.length > 0) {
								if (params.openLeftPanel === true) {
									app.panel.left.open();
								}

								if (leftView.history && leftView.history.length && leftView.history.indexOf('/notifications/') != -1) {
									leftView.router.back('/notifications/', { ignoreCache: true, force: true });
								} else {
									leftView.router.navigate('/notifications/');
								}

							} else {
								self.methods.customNotification({ title: LANGUAGE.PROMPT_MSG019 });

								var notificationsIconEl = $$('.openNotificationsPageLink i');
								if (notificationsIconEl && notificationsIconEl.length) {
									notificationsIconEl.empty();
								}
							}
						}

					} else {
						//console.log(result);
					}
				},
					function (xhr, status) {
						console.log(xhr);
						console.log(status);
						if (params && params.showLoader === true) {
							app.preloader.hide();
						}

						if (params && params.ptr === true) {
							app.ptr.get('.ptr-content-notifications').done();
						}

					},
					'json');
			}
		},
		displayNewNotificationArrived: function (list) {
			var self = this;

			if (list && list.length) {
				var currentRoute = leftView.router.currentRoute;
				if (currentRoute && currentRoute.name != 'notifications') {
					var notificationsIconEl = $$('.openNotificationsPageLink i');
					if (notificationsIconEl && notificationsIconEl.length) {
						var badge = notificationsIconEl.find('.badge');
						if (badge && badge.length) {
							var currentNotificationCount = parseInt(badge.text(), 10);
							if (currentNotificationCount) {
								if (currentNotificationCount < 99) {
									currentNotificationCount += list.length;
								} else {
									currentNotificationCount = '99+';
								}
							} else {
								currentNotificationCount = list.length;
							}
							badge.text(currentNotificationCount);

						} else {
							notificationsIconEl.html('<span class="badge color-red">' + list.length + '</span>');
						}
					}
				} else {
					var notificationList = app.virtualList.get('.notificationList');
					if (notificationList) {
						notificationList.prependItems(list);
					}
				}

				var notificationDetails = {
					subtitle: list[0].alarm == 'AD' ? 'NOTICE' : list[0].alarm,
					text: list[0].AssetName,
				};
				if (list.length > 1) {
					notificationDetails = {
						subtitle: LANGUAGE.PROMPT_MSG035 + '(' + list.length + ')',
						text: '',
					};
				}

				app.notification.create({
					title: self.name,
					titleRightText: LANGUAGE.COM_MSG29, //now
					subtitle: notificationDetails.subtitle,
					text: notificationDetails.text,
					closeOnClick: true,
					closeButton: true,
					on: {
						click: function () {
								if (list.length > 1) {
										if (leftView.history && leftView.history.length && leftView.history.indexOf('/notifications/') != -1) {
											leftView.router.back('/notifications/', { ignoreCache: true, force: true });
										} else {
											leftView.router.navigate('/notifications/');
										}
									
									
								} else {
									if(list[0].alarm == 'AD'){
										window.open(list[0].message, '_blank');
									}else{
										leftView.router.navigate('/notification/' + list[0].UniqueId + '/');
									}
								}
							//}
						},
					},
				}).open();
			}
		},
		setNotificationList: function (list) {
			var self = this;

			var pushList = self.methods.getFromStorage('notifications');
			var user = localStorage.ACCOUNT;

			if (pushList) {
				if (!pushList[user]) {
					pushList[user] = [];
				}
			} else {
				pushList = {};
				pushList[user] = [];
			}

			if (Array.isArray(list)) {
				list = self.methods.formatNewNotifications(list);
				for (var i = 0; i < list.length; i++) {
					list[i].UniqueId = app.utils.id();
					pushList[user].unshift(list[i]);
				}

				self.methods.displayNewNotificationArrived(list);
			}
			localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.NOTIFICATIONS", JSON.stringify(pushList));
		},
		deleteNotifications: function (deleteList, deleteAll) {
			var self = this;
			var pushList = self.methods.getFromStorage('notifications');
			var user = localStorage.ACCOUNT;
			if (deleteList && deleteList.length) {
				if (pushList && pushList[user] && pushList[user].length) {
					$.each(deleteList, function (key, val) {
						var index = pushList[user].map(function (e) { return e.UniqueId; }).indexOf(val);
						pushList[user].splice(index, 1);
					});
					localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.NOTIFICATIONS", JSON.stringify(pushList));
				}
			} else if (deleteAll) {
				if (pushList && pushList[user] && pushList[user].length) {
					pushList[user] = [];
					localStorage.setItem("COM.QUIKTRAK.QUIKLOC8.NOTIFICATIONS", JSON.stringify(pushList));
					var virtualList = self.virtualList.get('.notificationList');
					if (virtualList) {
						virtualList.deleteAllItems();
					}
				}
			}
		},
		calculateAlarmsDashboard: function (alarmLog) {
			let self = this;

			let ret = {
				All: 0,
				PowerDisconnect: 0,
				LowBattery: 0,
				Input1: 0,
				Input2: 0,
				Input3: 0,
				FatigueDriving: 0,
				/*Input3: 0,
				Input4: 0,
				Output1: 0,
				Output2: 0,*/
				Vibrate: 0,
				ACCON: 0,
				ACCOFF: 0,
				Speeding: 0,
				//Geofence: 0,			
				InGeoFance: 0,
				OutGeoFance: 0,
				//BilgeAlarm: 0,
				LowTemp: 0,
				HighTemp: 0,
				Other: 0,
			};
			if (!self.methods.isObjEmpty(alarmLog)) {

				//console.log('alarmLog', alarmLog)
				let keys = Object.keys(alarmLog);
				for (const key of keys) {
					//ret.push(groupList[key]);
					switch (key) {
						case Protocol.PositionAlerts.ACCON.toString():
							ret.ACCON = alarmLog[key];
							break;

						case Protocol.PositionAlerts.ACCOFF.toString():
							ret.ACCOFF = alarmLog[key];
							break;
						case Protocol.PositionAlerts.LowTemp.toString():
							ret.LowTemp = alarmLog[key];
							break;

						case Protocol.PositionAlerts.HighTemp.toString():
							ret.HighTemp = alarmLog[key];
							break;


						case Protocol.PositionAlerts.LowPower.toString(): //'512':
							ret.LowBattery = alarmLog[key];
							break;

						case Protocol.PositionAlerts.ElectricCutoff.toString(): //'4':
							ret.PowerDisconnect = alarmLog[key];
							break;

						case Protocol.PositionAlerts.HighSpeed.toString(): //'32':
							ret.Speeding = alarmLog[key];
							break;

						case Protocol.PositionAlerts.INPUT1.toString(): //'131072':
							ret.BilgeAlarm = alarmLog[key];
							ret.Input1 = alarmLog[key];
							break;

						case Protocol.PositionAlerts.INPUT2.toString(): //'262144':
							ret.Input2 = alarmLog[key];
							break;

						case Protocol.PositionAlerts.INPUT3.toString(): //'262144':
							ret.Input3 = alarmLog[key];
							break;

						case Protocol.PositionAlerts.InGeoFance.toString(): //'':
							ret.InGeoFance = alarmLog[key];
							break;

						case Protocol.PositionAlerts.OutGeoFance.toString(): //'':
							ret.OutGeoFance = alarmLog[key];
							break;

						case Protocol.PositionAlerts.Vibrate.toString(): //'':
							ret.Vibrate = alarmLog[key];
							break;

						case Protocol.PositionAlerts.FatigueDriving.toString(): //'':
							ret.FatigueDriving = alarmLog[key];
							break;

						/*	case Protocol.PositionAlerts.INPUT3.toString(): //'262144':
								ret.Input3 = alarmLog[key];
								break;
							case Protocol.PositionAlerts.INPUT4.toString(): //'262144':
								ret.Input4 = alarmLog[key];
								break;*/
						case Protocol.PositionAlerts.InGeoFance.toString(): //'8':
						case Protocol.PositionAlerts.OutGeoFance.toString(): //'16':
							ret.Geofence += alarmLog[key];
							break;


						default:
							ret.Other += alarmLog[key];
					}

					ret.All += alarmLog[key];
				}
			}
			//console.log(ret)

			return ret;
		},
		formatNewNotifications: function (messageList) {
			var self = this;

			var newMessageList = [];
			var msg = null;
			var msgTemp = null;
			var popped = null;
			if (Array.isArray(messageList)) {
				for (var i = 0; i < messageList.length; i++) {
					msg = null;
					msgTemp = null;
					popped = null;
					if (messageList[i].payload) {
						msg = self.methods.isJsonString(messageList[i].payload);
						if (!msg) {
							msg = messageList[i].payload;
						}
					} else {
						msg = self.methods.isJsonString(messageList[i]);
						if (!msg) {
							msg = messageList[i];
						}
					}
					if (msg) {
						if (msg.PositionTime) {
							localTime = moment.utc(msg.PositionTime).toDate();
							msg.PositionTime = moment(localTime).format(window.COM_TIMEFORMAT);
						}
						if (msg.time) {
							localTime = moment.utc(msg.time).toDate();
							msg.time = moment(localTime).format(window.COM_TIMEFORMAT);
						}
						if (msg.CreateDateTime) {
							localTime = moment.utc(msg.CreateDateTime).toDate();
							msg.CreateDateTime = moment(localTime).format(window.COM_TIMEFORMAT);
						}
						if (msg.lat) {
							msg.Lat = msg.lat;
						}
						if (msg.lng) {
							msg.Lng = msg.lng;
						}
						if (msg.title && msg.alarm != 'AD') {
							msg.alarm = msg.title;
						}
						if (msg.imei) {
							msg.Imei = msg.imei;
						}
						if (msg.name) {
							msg.AssetName = msg.name;
						}
						if (msg.speed) {
							msg.Speed = msg.speed;
						}
						if (msg.direct) {
							msg.Direction = msg.direct;
						}
						if (msg.time) {
							msg.CreateDateTime = msg.time;
						}

						msgTemp = msg;
						popped = newMessageList.pop();
						if (popped) {
							popped = JSON.stringify(popped);
							msgTemp = JSON.stringify(msgTemp);

							if (popped != msgTemp) {
								popped = JSON.parse(popped);
								newMessageList.push(popped);
							}
						}

						newMessageList.push(msg);
					}
				}
			}
			return newMessageList;
		},
		formatStatusMessage: function (message) {
			var self = this;

			var assetList = self.methods.getFromStorage('assetList');
			var asset = assetList[message.Imei];
			var assetImg = self.methods.getAssetImg(asset, { 'assetEdit': true });
			if (!message.Direct && message.Direction) {
				message.Direct = message.Direction;
			}
			var deirectionCardinal = Protocol.Helper.getDirectionCardinal(message.Direct);

			if (assetImg) {
				message.AssetImg = assetImg;
			}

			message.AccColor = 'text-color-red';
			if (message.Acc && message.Acc == 'ON') {
				message.AccColor = 'text-color-green';
			}

			if (message.Direction) {
				message.Direction = deirectionCardinal + '(' + message.Direct + '&deg)';
			}

			if (asset && message.Mileage) {
				message.Mileage = Protocol.Helper.getMileage(asset, message.Mileage);
			}
			if (asset && message.LaunchHours) {
				message.EngineHours = Protocol.Helper.getEngineHours(asset, message.LaunchHours);
			}
			if (asset && message.Speed) {
				message.Speed = Protocol.Helper.getSpeedValue(asset.Unit, message.Speed) + ' ' + Protocol.Helper.getSpeedUnit(asset.Unit);
			} else if (asset && typeof (message.Speed) != 'undefined') {
				message.Speed = message.Speed + ' ' + Protocol.Helper.getSpeedUnit(asset.Unit);
			}

			var deviceParams = message.PARAMS ? self.methods.isJsonString(message.PARAMS) : '';
			if (deviceParams) {
				message.PARAMS = self.methods.isJsonString(message.PARAMS);
			}


			return message;
		},
		formatPlaybackData: function (historyData, asset) {
			var formattedData = {};
			var userInfo = app.methods.getFromStorage('userInfo');
			if (historyData) {
				var deirectionCardinal = Protocol.Helper.getDirectionCardinal(historyData.direct);
				//let newPosDateTime = moment(positionData.DateTime,'DD/MM/YYYY HH:mm:ss').utc().add(userInfo.UserInfo.TimeZone, 'hours').add(app.data.UTCOFFSET,'minutes').format('DD/MM/YYYY HH:mm:ss');
	               //console.log(userInfo.UserInfo.TimeZone, app.data.UTCOFFSET)
				formattedData.Lat = historyData.lat;
				formattedData.Lng = historyData.lng;
				formattedData.Coords = parseFloat(historyData.lat).toFixed(5) + ', ' + parseFloat(historyData.lng).toFixed(5);
				formattedData.DateTime = moment.utc(historyData.positionTime, 'X').add(userInfo.UserInfo.TimeZone, 'hours').format(window.COM_TIMEFORMAT);//.add(app.data.UTCOFFSET,'minutes')
				formattedData.Speed = Protocol.Helper.getSpeedValue(asset.Unit, historyData.speed) + ' ' + Protocol.Helper.getSpeedUnit(asset.Unit);
				formattedData.Direction = deirectionCardinal + '(' + historyData.direct + '&deg)';
				formattedData.Mileage = (Protocol.Helper.getMileageValue(asset.Unit, historyData.mileage) + parseInt(asset.InitMileage) + parseInt(asset._FIELD_FLOAT7)) + '&nbsp;' + Protocol.Helper.getMileageUnit(asset.Unit);

			} else {
				console.log('data object is empty');
			}
			return formattedData;
		},
		formatPlaybackEventData: function (point = {}, geofenceList) {
			let self = this;
			var userInfo = app.methods.getFromStorage('userInfo');
			/*point.BeginTimeLocal = moment(point.beginTime).format(window.COM_TIMEFORMAT);
			point.BeginTimeLocal = moment.utc(point.BeginTimeLocal).toDate();
			point.BeginTimeLocal = moment(point.BeginTimeLocal).local().format(window.COM_TIMEFORMAT);*/
			//console.log('111',point)
			point.BeginTimeLocal = moment(point.beginTime).format(window.COM_TIMEFORMAT);
			point.BeginTimeLocal = moment.utc(point.BeginTimeLocal).toDate();//.add(app.data.UTCOFFSET,'minutes')
			point.BeginTimeLocal = moment(point.BeginTimeLocal).local().format(window.COM_TIMEFORMAT);


			/* point.EndTimeLocal = moment(point.endTime).format(window.COM_TIMEFORMAT);
				   point.EndTimeLocal = moment.utc(point.EndTimeLocal).toDate();
				   point.EndTimeLocal = moment(point.EndTimeLocal).local().format(window.COM_TIMEFORMAT);*/

			switch (point.eventClass) {
				case 1:
					point.IconBg = 'bg-color-red';
					point.Icon = 'icon-admin-alarms';

					switch (point.eventType) {
						case 8:
							point.EventName = LANGUAGE.ASSET_ALARM_MSG12;
							point.IconBg = 'bg-color-green';
							point.Icon = 'icon-admin-geofences';
							point.OtherName = self.methods.getGeofenceName(point.otherCode, geofenceList);
							break;
						case 16:
							point.EventName = LANGUAGE.ASSET_ALARM_MSG13;
							point.IconBg = 'bg-color-red';
							point.Icon = 'icon-admin-geofences';
							point.OtherName = self.methods.getGeofenceName(point.otherCode, geofenceList);
							break;
						default:
							$.each(Protocol.PositionAlerts, function (key, val) {
								if (val == point.eventType) {
									point.EventName = key;
								}
							});
					}
					break;

				case 2:     // ACC
					point.Icon = 'icon-ignition';
					if (point.eventType === 0) {
						point.IconBg = 'bg-color-gray';
						point.EventName = LANGUAGE.ASSET_ALARM_MSG10;
					} else {
						point.IconBg = 'bg-color-green';
						point.EventName = LANGUAGE.ASSET_ALARM_MSG11;
					}
					break;

				case 4:     // ACTIVE
					point.Icon = 'icon-header-tracking';
					point.Duration = Protocol.Helper.getDifferenceBTtwoDates(point.beginTime, point.endTime);
					point.Duration = moment.duration(point.Duration, "milliseconds").format('d[d] h[h] m[m] s[s]');
					if (point.eventType === 0) {
						point.IconBg = 'bg-color-gray';
						point.EventName = LANGUAGE.HOME_MSG015;
					} else {
						point.IconBg = 'bg-color-green';
						point.EventName = LANGUAGE.HOME_MSG014;
					}
					break;
			}

			return point;
		},
		formatLotOverviewReportData: function (arry = []) {
			let ret = [];

			let groupList = this.methods.getFromStorage("groupList");
			let assetList = this.methods.getFromStorage("assetList");
			for (var i = arry.length - 1; i >= 0; i--) {
				arry[i].StorageTime = assetList[arry[i].IMEI].StorageTime;
				arry[i].InInventoryTime = Protocol.Helper.getDifferenceBTtwoDates(arry[i].StorageTime, moment().utc());
				arry[i].InInventoryTimeFormatted = moment.duration(arry[i].InInventoryTime, "milliseconds").format('d [days]');
				if (arry[i].OUT_LIST) {
					for (var y = arry[i].OUT_LIST.length - 1; y >= 0; y--) {
						arry[i].OUT_LIST[y].BeginTimeLocal = moment(arry[i].OUT_LIST[y].BEGIN_TIME, 'YYYY/MM/DD HH:mm:ss').add(app.data.UTCOFFSET, 'minutes').format('DD/MM/YYYY HH:mm:ss');
						arry[i].OUT_LIST[y].Duration = moment.duration(Protocol.Helper.getDifferenceBTtwoDates(moment(arry[i].OUT_LIST[y].BEGIN_TIME, 'YYYY/MM/DD HH:mm:ss'), moment(arry[i].OUT_LIST[y].END_TIME, 'YYYY/MM/DD HH:mm:ss')), "milliseconds").format('d[d] h[h] m[m]');
					}
				}
				let index = ret.findIndex(el => el.IOT_CODE == arry[i].IOT_CODE);
				if (index == -1) {
					let fenceIndex = groupList.findIndex(el => el.Code == arry[i].IOT_CODE);
					let tempObj = {
						IOT_CODE: arry[i].IOT_CODE,
						IOT_NAME: arry[i].IOT_NAME,
						OUT_COUNT: arry[i].OUT_COUNT,
						Assets: [arry[i]],
						TotalAssignedAssets: groupList[fenceIndex].Assets.length,
						GeoType: groupList[fenceIndex].GeoType,
						GeoPolygon: groupList[fenceIndex].GeoPolygon,
						Radius: groupList[fenceIndex].Radius,
						Lat: groupList[fenceIndex].Lat,
						Lng: groupList[fenceIndex].Lng
					}
					ret.push(tempObj);
				} else {
					ret[index].Assets.push(arry[i]);
					ret[index].OUT_COUNT += arry[i].OUT_COUNT;
				}


			}

			return ret;
		},
		formatGeofenceReportData: function (arry = []) {
			let ret = [];

			let geofenceList = this.methods.getFromStorage("geofenceList");
			let groupList = this.methods.getFromStorage("groupList");

			let GeofenceAndGeogroupList = [];
			let keys = Object.keys(geofenceList);
			for (const key of keys) {
				GeofenceAndGeogroupList.push(geofenceList[key]);
			}
			GeofenceAndGeogroupList.push(...groupList);
			//console.log(GeofenceAndGeogroupList);
			for (var i = arry.length - 1; i >= 0; i--) {
				if (arry[i].BeginTime) {
					arry[i].BeginTimeLocal = moment(arry[i].BeginTime, 'YYYY/MM/DD HH:mm:ss').add(app.data.UTCOFFSET, 'minutes').format('DD/MM/YYYY HH:mm:ss');
				}
				if (arry[i].TimeSpan) {
					arry[i].TimeSpanConverted = moment.duration(parseInt(arry[i].TimeSpan, 10), "minutes").format('d[d] h[h] m[m]');
				}
				let index = ret.findIndex(el => el.Geofence == arry[i].Geofence);
				if (index == -1) {
					let fenceIndex = GeofenceAndGeogroupList.findIndex(el => el.Code == arry[i].Geofence);
					let tempObj = {
						Geofence: arry[i].Geofence,
						GeofenceName: arry[i].GeofenceName,
						DetailsOut: [],
						DetailsIn: [],

						TotalAssignedAssets: GeofenceAndGeogroupList[fenceIndex].SelectedAssetList ? GeofenceAndGeogroupList[fenceIndex].SelectedAssetList.length : GeofenceAndGeogroupList[fenceIndex].Assets.length,
						GeoType: GeofenceAndGeogroupList[fenceIndex].GeoType,
						GeoPolygon: GeofenceAndGeogroupList[fenceIndex].GeoPolygon,
						Radius: GeofenceAndGeogroupList[fenceIndex].Radius,
						Lat: GeofenceAndGeogroupList[fenceIndex].Lat,
						Lng: GeofenceAndGeogroupList[fenceIndex].Lng
					}

					arry[i].EventType == 16 ? tempObj.DetailsOut.push(arry[i]) : tempObj.DetailsIn.push(arry[i]);
					ret.push(tempObj);
				} else {
					arry[i].EventType == 16 ? ret[index].DetailsOut.push(arry[i]) : ret[index].DetailsIn.push(arry[i]);
				}
			}

			/*for (var i = ret.length - 1; i >= 0; i--) {
	  
				  }*/
			return ret;
		},
		getPlaybackMarkerDataTable: function (asset, point) {
			var markerData = '';
			if (asset) {
				var assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(asset);
				if (assetFeaturesStatus && assetFeaturesStatus.stats) {
					var speed = 0;
					var mileage = '-';
					var direct = point.direct;
					var deirectionCardinal = Protocol.Helper.getDirectionCardinal(direct);
					if (typeof asset.Unit !== "undefined" && typeof asset.posInfo.speed !== "undefined") {
						speed = Protocol.Helper.getSpeedValue(asset.Unit, point.speed) + ' ' + Protocol.Helper.getSpeedUnit(asset.Unit);
					}
					if (typeof asset.Unit !== "undefined" && typeof asset.posInfo.mileage !== "undefined" && asset.posInfo.mileage != '-') {
						mileage = (Protocol.Helper.getMileageValue(asset.Unit, point.mileage) + parseInt(asset.InitMileage) + parseInt(asset._FIELD_FLOAT7)) + '&nbsp;' + Protocol.Helper.getMileageUnit(asset.Unit);
					}
					var time = moment(point.positionTime, 'X').format(window.COM_TIMEFORMAT);

					var customAddress = !point.customAddress ? LANGUAGE.COM_MSG08 : point.customAddress;


					markerData += '<table cellpadding="0" cellspacing="0" border="0" class="marker-data-table">';

					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.NOTIFICATIONS_MSG01 + '</td>';
					markerData += '<td class="marker-data-value">' + time + '</td>';
					markerData += '</tr>';
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.NOTIFICATIONS_MSG03 + '</td>';
					markerData += '<td class="marker-data-value">' + mileage + '</td>';
					markerData += '</tr>';
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.NOTIFICATIONS_MSG16 + '</td>';
					markerData += '<td class="marker-data-value">' + speed + '</td>';
					markerData += '</tr>';

					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.NOTIFICATIONS_MSG02 + '</td>';
					markerData += '<td class="marker-data-value">' + deirectionCardinal + ' (' + direct + '&deg;)</td>';
					markerData += '</tr>';
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">GPS</td>';
					markerData += '<td class="marker-data-value ">' + parseFloat(point.lat).toFixed(5) + ', ' + parseFloat(point.lng).toFixed(5) + '</td>';
					markerData += '</tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG012 + '</td>';
					markerData += '<td class="marker-data-value marker-address">' + customAddress + '</td>';
					markerData += '</tr>';

					markerData += '</table>';
				}
			}
			return markerData;
		},
		getPlaybackMarkerDataTableInfoPin: function (point, additionaDataObj = {}, isHistory = false) {
			var self = this;
			var markerData = '';
			//console.log(point, additionaDataObj)
			var beginTime = moment(point.beginTime).format(window.COM_TIMEFORMAT);
			beginTime = moment.utc(beginTime).toDate();
			beginTime = moment(beginTime).local().format(window.COM_TIMEFORMAT);
			var endTime = moment(point.endTime).format(window.COM_TIMEFORMAT);
			endTime = moment.utc(endTime).toDate();
			endTime = moment(endTime).local().format(window.COM_TIMEFORMAT);
			var posTime = moment(point.positionTime).format(window.COM_TIMEFORMAT);
			posTime = moment.utc(posTime).toDate();
			posTime = moment(posTime).local().format(window.COM_TIMEFORMAT);
			

			var dateDifference = Protocol.Helper.getDifferenceBTtwoDates(point.beginTime, point.endTime);
			var duration = moment.duration(dateDifference, "milliseconds").format('d[d] h[h] m[m] s[s]');
			var fenceName = '';

			markerData += '<table cellpadding="0" cellspacing="0" border="0" class="marker-data-table">';
			switch (point.eventClass) {
				case 1:
					switch (point.eventType) {
						case 8:
							markerData += '<tr>';
							markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG15 + '</td>';
							markerData += '<td class="marker-data-value">' + LANGUAGE.ASSET_ALARM_MSG12 + '</td>';
							markerData += '</tr>';
							if (additionaDataObj.GeofenceList && additionaDataObj.GeofenceList.length) {
								fenceName = self.methods.getGeofenceName(point.otherCode, additionaDataObj.GeofenceList);
								if (fenceName) {
									markerData += '<tr>';
									markerData += '<td class="marker-data-caption">' + LANGUAGE.GEOFENCES_MSG04 + '</td>';
									markerData += '<td class="marker-data-value">' + fenceName + '</td>';
									markerData += '</tr>';
								}
							}
							break;

						case 16:
							markerData += '<tr>';
							markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG15 + '</td>';
							markerData += '<td class="marker-data-value">' + LANGUAGE.ASSET_ALARM_MSG13 + '</td>';
							markerData += '</tr>';
							if (additionaDataObj.GeofenceList && additionaDataObj.GeofenceList.length) {
								fenceName = self.methods.getGeofenceName(point.otherCode, additionaDataObj.GeofenceList);
								if (fenceName) {
									markerData += '<tr>';
									markerData += '<td class="marker-data-caption">' + LANGUAGE.GEOFENCES_MSG04 + '</td>';
									markerData += '<td class="marker-data-value">' + fenceName + '</td>';
									markerData += '</tr>';
								}
							}
							break;

						default:
							markerData += '<tr>';
							markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG15 + '</td>';
							$.each(Protocol.PositionAlerts, function (key, val) {
								if (val == point.eventType) {
									markerData += '<td class="marker-data-value">' + key + '</td>';
								}
							});
							markerData += '</tr>';
					}
					break;

				case 2:     // ACC
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG006 + '</td>';    //Ignition
					if (point.eventType === 0) {
						markerData += '<td class="marker-data-value">' + LANGUAGE.COM_MSG93 + '</td>'; //off
					} else {
						markerData += '<td class="marker-data-value">' + LANGUAGE.COM_MSG94 + '</td>'; //on
					}
					markerData += '</tr>';
					break;

				case 4:     // ACTIVE
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG08 + '</td>';    //Activity
					if (point.eventType === 0) {
						markerData += '<td class="marker-data-value">' + LANGUAGE.HOME_MSG015 + '</td>';   //Stopped
					} else {
						markerData += '<td class="marker-data-value">' + LANGUAGE.HOME_MSG014 + '</td>';  //Move
					}
					markerData += '</tr>';
					break;
			}
			
        let userInfo = self.methods.getFromStorage('userInfo');
		
			if (beginTime == endTime) {
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG14 + '</td>';
				markerData += '<td class="marker-data-value">' + (point?.positionTime ? moment.unix(point?.positionTime).format(window.COM_TIMEFORMAT) : beginTime) + '</td>';//beginTime
				markerData += '</tr>';
			} else {
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG09 + '</td>';
				markerData += '<td class="marker-data-value">' + beginTime + '</td>';
				markerData += '</tr>';
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG10 + '</td>';
				markerData += '<td class="marker-data-value">' + endTime + '</td>';
				markerData += '</tr>';
			}

			if (beginTime != endTime) {
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_PLAYBACK_MSG11 + '</td>';
				markerData += '<td class="marker-data-value">' + duration + '</td>';
				markerData += '</tr>';
			}

				let sp = point?.speed ? point?.speed : '0';
				let bt = point?.battery ? point?.battery : point?.alt;
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">Speed</td>';
				markerData += '<td class="marker-data-value">' + sp  + 'km/h</td>';
				markerData += '</tr>';
				
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">Battery</td>';
				markerData += '<td class="marker-data-value">' +  self.methods.getBatteryValue( point.pclass, bt ) + ' ' + self.methods.getBatteryUnit(point.pclass, bt) + '</td>';
				markerData += '</tr>';
				
				
			markerData += '<tr>';
			markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG012 + '</td>';
			markerData += '<td class="marker-data-value marker-address" data-popupIdAddress="' + point.index + '">' + LANGUAGE.COM_MSG08 + '</td>';
			markerData += '</tr>';

			markerData += '</table>';
			//console.log('poiny', point)

			return markerData;
		},
		
getBatteryValue: function(classBattery, batteryValue) {
  let ret = 'No data';

  switch (classBattery){

      case ('TIANQIN_LK3GP')://%
      case ('GPT19H'):
      case ('JT808_GLOCK'):
        ret = batteryValue
      break;

      case ('GOT 20'):
      case ('GOT20'):
		  if(batteryValue <= 5){
			if (batteryValue >= 0 && batteryValue <= 3.39) {
			  ret = 0;
			}
			else if (batteryValue >= 3.39 && batteryValue <= 3.45) {
				ret = 20;
			}
			else if (batteryValue > 3.45 && batteryValue <= 3.54) {
				ret = 40;
			}
			else if (batteryValue > 3.54 && batteryValue <= 3.72) {
				ret = 60;
			}
			else if (batteryValue > 3.72 && batteryValue <= 3.8927) {
				ret = 80;
			}
			else {
				ret = 100;
			}
		  }else{
			ret = batteryValue
		  }
		  break;
      case ('EELINK_OBD'): //12 v
      case ('VT600_3G'): //25
      case ('KKS')://12
      case ('TIANQIN_EN4G')://27
      case ('VT600')://12
      case ('EELINK_TEMP')://12
      case ('TIANQIN_LK3GV2')://12
      //case ('GOT10')://25
        ret = batteryValue
      break;
      
      case ('AVL05'): //no data
      case ('AVL09'):
      case ('HONGYUAN_V'):
      case ('RUPTELA'):
      case ('TIANQIN_QT525'):
      case ('VT600_FUEL'):
      case ('SINOCASTEL'):
      case ('HONGYUAN'):
      case ('JT808_KMXXX'):
      case ('VT900_DOOR'):
      case ('TIANQIN_LK3G'):
      case ('TIANQIN_QT206'):
      case ('TIANQIN_QTPTW'):
      case ('VJOY'):
      case ('BSJV3'):
      case ('TKSTAR'):
      case ('OUNING_WATCH'):
      case ('TKXXX'):
      case ('PHONE_TRACK'):
      case ('GOT10'):
        ret = 'No data'
      break;
  }
  
  return ret
},
getBatteryUnit: function(classBattery, batteryValue) {
  let ret = '';

  switch (classBattery){
    case ('TIANQIN_LK3GP')://%
    case ('GPT19H'):
    case ('JT808_GLOCK'):
      ret = '%'
    break;

    case ('GOT 20'):
    case ('GOT20'):
      if(batteryValue <= 5){
        ret = '%'
      }else{
        ret = 'V'
      }
    break;
    case ('EELINK_OBD'): //12 v
    case ('VT600_3G'): //25
    case ('KKS')://12
    case ('TIANQIN_EN4G')://27
    case ('VT600')://12
    case ('EELINK_TEMP')://12
    case ('TIANQIN_LK3GV2')://12
    //case ('GOT10')://25
      ret = 'V'
    break;
  }
  
  return ret
},
		getPlaybackFilterHistoryList: function() {
			return [
				{
					Name: LANGUAGE.ASSET_ALARM_MSG11,  //Ignition On
					Value: '1',
					IconBg: 'bg-color-green',
					Icon: 'icon-ignition',
					IconHTML: `<div class='user-icon text-align-center text-color-white bg-color-green display-flex align-items-center justify-content-center text-transform-uppercase'>
                                    <i class='f7-icons size-16 line-height-icon-fix icon-ignition '></i> 
                                </div>`,
				},
				{
					Name: LANGUAGE.ASSET_ALARM_MSG11,  //Ignition Off
					Value: '2',
					IconBg: 'bg-color-gray',
					Icon: 'icon-ignition',
					IconHTML: `<div class='user-icon text-align-center text-color-white bg-color-green display-flex align-items-center justify-content-center text-transform-uppercase'>
                                    <i class='f7-icons size-16 line-height-icon-fix icon-ignition '></i> 
                                </div>`,
				},
			]
		},
		getPlaybackFilterEventsList: function () {
			return [
				{
					Name: LANGUAGE.ASSET_ALARM_MSG11,  //Ignition On
					Value: '1',
					IconBg: 'bg-color-green',
					Icon: 'icon-ignition',
					IconHTML: `<div class='user-icon text-align-center text-color-white bg-color-green display-flex align-items-center justify-content-center text-transform-uppercase'>
                                    <i class='f7-icons size-16 line-height-icon-fix icon-ignition '></i> 
                                </div>`,
				},
				{
					Name: LANGUAGE.HOME_MSG015,  //Stopped
					Value: '2',
					IconBg: 'bg-color-gray',
					Icon: 'icon-header-tracking',
					IconHTML: `<div class='user-icon text-align-center text-color-white bg-color-gray display-flex align-items-center justify-content-center text-transform-uppercase'>
                                    <i class='f7-icons size-16 line-height-icon-fix icon-header-tracking '></i> 
                                </div>`,

				},
				{
					Name: LANGUAGE.ASSET_ALARM_MSG12,  //Enter Geofence
					Value: '3',
					IconBg: 'bg-color-green',
					Icon: 'icon-admin-geofences',
					IconHTML: `<div class='user-icon text-align-center text-color-white bg-color-green display-flex align-items-center justify-content-center text-transform-uppercase'>
                                    <i class='f7-icons size-16 line-height-icon-fix icon-admin-geofences '></i> 
                                </div>`,
				},
				{
					Name: LANGUAGE.ASSET_ALARM_MSG13,  //Leave Geofence
					Value: '4',
					IconBg: 'bg-color-red',
					Icon: 'icon-admin-geofences',
					IconHTML: `<div class='user-icon text-align-center text-color-white bg-color-red display-flex align-items-center justify-content-center text-transform-uppercase'>
                                    <i class='f7-icons size-16 line-height-icon-fix icon-admin-geofences '></i> 
                                </div>`,
				},
				{
					Name: LANGUAGE.ASSET_PLAYBACK_MSG18,  //Other Alarms
					Value: '5',
					IconBg: 'bg-color-red',
					Icon: 'icon-admin-alarms',
					IconHTML: `<div class='user-icon text-align-center text-color-white bg-color-red display-flex align-items-center justify-content-center text-transform-uppercase'>
                                    <i class='f7-icons size-16 line-height-icon-fix icon-admin-alarms '></i> 
                                </div>`,
				},
			];
		},
		getGeofenceDataTable: function (geofence, options) {
			var self = this;
			var markerData = '';
			if (geofence) {
				let assignedAssets = '';
				let assetList = self.methods.getFromStorage('assetList');// getAssetList();
				let assignedAssetsCount = '0';
				let BeginTime = '';
				let EndTime = '';
				let IgnoreDays = '';

				if (options && options.geogroup) {
					if (geofence.Assets && geofence.Assets.length) {
						assignedAssetsCount = geofence.Assets.length;
						for (var i = geofence.Assets.length - 1; i >= 0; i--) {
							assignedAssets += geofence.Assets[i].Name + ', ';
						}
					}
				} else {
					if (geofence.SelectedAssetList && geofence.SelectedAssetList.length) {
						assignedAssetsCount = geofence.SelectedAssetList.length;
						for (var i = geofence.SelectedAssetList.length - 1; i >= 0; i--) {
							if (assetList[geofence.SelectedAssetList[i].IMEI]) {
								assignedAssets += assetList[geofence.SelectedAssetList[i].IMEI].Name + ', ';
							} else {
								assignedAssets += LANGUAGE.COM_MSG27 + ', ';
							}
						}
					}
				}
				if (assignedAssets) {
					assignedAssets = assignedAssets.slice(0, -2);
				} else {
					assignedAssets = LANGUAGE.COM_MSG111;
				}

				if (geofence.Week && geofence.Week.length) {
					for (var i = 0; i < geofence.Week.length; i++) {
						IgnoreDays += geofence.Week.length > 2 ? Protocol.DaysOfWeek[geofence.Week[i].Week].nameSmall + ', ' : Protocol.DaysOfWeek[geofence.Week[i].Week].name + ', ';
					}
					if (IgnoreDays) {
						IgnoreDays = IgnoreDays.slice(0, -2);
					}
					BeginTime = geofence.Week[0].BeginTime ? moment(geofence.Week[0].BeginTime, 'HH:mm:ss').add(app.data.UTCOFFSET, 'minutes').format('HH:mm:ss') : BeginTime;
					EndTime = geofence.Week[0].EndTime ? moment(geofence.Week[0].EndTime, 'HH:mm:ss').add(app.data.UTCOFFSET, 'minutes').format('HH:mm:ss') : EndTime;
				}


				markerData += `
                <table cellpadding="0" cellspacing="0" border="0" class="marker-data-table">
                    <tr>
                       <td class="marker-data-caption">${options && options.geogroup ? LANGUAGE.ASSET_GROUPS_MSG10 : LANGUAGE.GEOFENCES_MSG05}</td>
                       <td class="marker-data-value">${geofence.Name}</td>
                    </tr>
                    <tr>
                        <td class="marker-data-caption">${LANGUAGE.COM_MSG104}(${assignedAssetsCount})</td>
                        <td class="marker-data-value">${assignedAssets}</td>
                    </tr>           
                    `;

				if (options && !options.geogroup) {
					markerData += `
                        <tr>
                            <td class="marker-data-caption">${LANGUAGE.GEOFENCES_MSG08}</td>
                            <td class="marker-data-value">${Protocol.Helper.getGeofenceAlertType(geofence.Alerts)}</td>
                        </tr>
                        <tr>
                           <td class="marker-data-caption">${LANGUAGE.COM_MSG112}</td>
                           <td class="marker-data-value">${geofence.State == 1 ? LANGUAGE.PROMPT_MSG075 : LANGUAGE.PROMPT_MSG076}</td>
                        </tr>
                        <tr>
                           <td class="marker-data-caption">${LANGUAGE.COM_MSG71}</td>
                           <td class="marker-data-value">${geofence.Inverse == 1 ? LANGUAGE.PROMPT_MSG075 : LANGUAGE.PROMPT_MSG076}</td>
                        </tr>
                    `;
					if (geofence.Inverse == 1) {
						markerData += `
                            <tr>
                               <td class="marker-data-caption">${LANGUAGE.GEOFENCES_MSG13}</td>
                               <td class="marker-data-value">${BeginTime} - ${EndTime}</td>
                            </tr>
                            <tr>
                               <td class="marker-data-caption">${LANGUAGE.COM_MSG72}</td>
                               <td class="marker-data-value">${IgnoreDays}</td>
                            </tr>
                        `;
					}
				}

				markerData += ` 
                    <tr>
                        <td class="marker-data-caption">${LANGUAGE.HOME_MSG011}</td>
                        <td class="marker-data-value ">${Protocol.Helper.convertDMS(geofence.Lat, geofence.Lng)}</td>
                    </tr>`;

				if (geofence.Address) {
					markerData += ` 
                    <tr>
                        <td class="marker-data-caption">${LANGUAGE.HOME_MSG012}</td>
                        <td class="marker-data-value address-${geofence.Code}">${geofence.Address}</td>
                    </tr>`;
				}
				markerData += ` 
                </table>`;
			}
			return markerData;
		},
		getAlarmMarkerDataTable: function (positionDetails) {
			let customAddress = !positionDetails.customAddress ? LANGUAGE.COM_MSG08 : positionDetails.customAddress;

			let markerData = `
            <table cellpadding="0" cellspacing="0" border="0" class="marker-data-table">
               <tr>
                   <td class="marker-data-caption">${LANGUAGE.HOME_MSG001}</td>
                   <td class="marker-data-value">${positionDetails.AssetName}</td>
               </tr>
               <tr>
                   <td class="marker-data-caption">${LANGUAGE.REPORT_PANEL_MSG56}</td>
                   <td class="marker-data-value">${positionDetails.AlertName}</td>
               </tr>
               <tr>
                   <td class="marker-data-caption">${LANGUAGE.REPORT_PANEL_MSG40}</td>
                   <td class="marker-data-value">${positionDetails.AlarmTimeLocal}</td>
               </tr>
               <tr>
                   <td class="marker-data-caption">${LANGUAGE.HOME_MSG005}</td>
                   <td class="marker-data-value">${positionDetails.Speed}</td>
               </tr>
               <tr>
                   <td class="marker-data-caption">${LANGUAGE.HOME_MSG012}</td>
                   <td class="marker-data-value">${customAddress}</td>
               </tr>
            </table>`;
			return markerData;
		},
		getMarkerDataTable: function (asset, positionDetails) {
			var self = this;
			var markerData = '';
			var customAddress = LANGUAGE.COM_MSG08;
			//console.log('positionDetails', positionDetails, asset, Protocol.Helper.getAssetStateInfo(asset))

			if (positionDetails) {
				customAddress = !positionDetails.customAddress ? LANGUAGE.COM_MSG08 : positionDetails.customAddress;
				markerData += '<table cellpadding="0" cellspacing="0" border="0" class="marker-data-table">';
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG001 + '</td>';
				markerData += '<td class="marker-data-value">' + positionDetails.AssetName + '</td>';
				markerData += '</tr>';
				if (self.data.CustomerType === 2 || self.data.CustomerType === 6) {
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_LIST_MSG22 + '</td>';
					markerData += '<td class="marker-data-value">' + positionDetails.StockNumber + '</td>';
					markerData += '</tr>';
				}

				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG003 + '</td>';
				markerData += '<td class="marker-data-value">' + positionDetails.PositionTime + '</td>';
				markerData += '</tr>';

				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG005 + '</td>';
				markerData += '<td class="marker-data-value">' + positionDetails.Speed + '</td>';
				markerData += '</tr>';
				if (positionDetails.type && parseInt(positionDetails.type, 10) === 32 && parseInt(asset.MaxSpeedAlertMode, 10) === 2 && !positionDetails.SpeedLimit) {
					positionDetails.SpeedLimit = Protocol.Helper.getSpeedValue(asset.Unit, asset.MaxSpeed) + ' ' + Protocol.Helper.getSpeedUnit(asset.Unit);
				}
				if (positionDetails.type && parseInt(positionDetails.type, 10) === 32) {
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.COM_MSG119 + '</td>';
					markerData += `<td class="marker-data-value">${positionDetails.SpeedLimit ? positionDetails.SpeedLimit : LANGUAGE.COM_MSG08}</td>`;
					markerData += '</tr>';
				}
				if (positionDetails.Direction) {
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG010 + '</td>';
					markerData += '<td class="marker-data-value">' + positionDetails.Direction + '</td>';
					markerData += '</tr>';
				}
				if (positionDetails.Mileage) {
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG004 + '</td>';
					markerData += '<td class="marker-data-value">' + positionDetails.Mileage + '</td>';
					markerData += '</tr>';
				}
				if (positionDetails.Acc) {
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG006 + '</td>';
					markerData += '<td class="marker-data-value">' + positionDetails.Acc + '</td>';
					markerData += '</tr>';
				}
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG011 + '</td>';
				markerData += '<td class="marker-data-value ">' + Protocol.Helper.convertDMS(positionDetails.Lat, positionDetails.Lng) + '</td>';
				markerData += '</tr>';
				markerData += '<tr>';
				markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG012 + '</td>';
				markerData += '<td class="marker-data-value address-' + positionDetails.Imei + '">' + customAddress + '</td>';
				markerData += '</tr>';
				markerData += '</table>';
			} else if (asset) {
				var assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(asset);
				if (assetFeaturesStatus && assetFeaturesStatus.stats) {
					var speed = 0;
					var mileage = '-';
					var launchHours = '';
					var positionType = Protocol.Helper.getPositionType(parseInt(asset.posInfo.positionType));
					deirectionCardinal = Protocol.Helper.getDirectionCardinal(asset.posInfo.direct);

					var contactList = this.methods.getFromStorage('contactList');
					var driver = null;
					if (asset && asset.DriverCode) {
						let index = contactList.findIndex((item) => item.Code === asset.DriverCode)
						driver = index !== -1 ? contactList[index] : null
					}

					if (typeof asset.Unit !== "undefined" && typeof asset.posInfo.speed !== "undefined") {
						speed = Protocol.Helper.getSpeedValue(asset.Unit, asset.posInfo.speed) + ' ' + Protocol.Helper.getSpeedUnit(asset.Unit);
					}
					if (typeof asset.Unit !== "undefined" && typeof asset.posInfo.mileage !== "undefined" && asset.posInfo.mileage != '-') {
						mileage = Protocol.Helper.getMileage(asset, asset.posInfo.mileage);
					}
					if (typeof asset.posInfo.launchHours !== "undefined") {
						launchHours = Protocol.Helper.getEngineHours(asset, asset.posInfo.launchHours);
					}
					customAddress = !asset.posInfo.customAddress ? LANGUAGE.COM_MSG08 : asset.posInfo.customAddress;

					markerData += '<table cellpadding="0" cellspacing="0" border="0" class="marker-data-table">';
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG001 + '</td>';
					markerData += '<td class="marker-data-value">' + asset.Name + '</td>';
					markerData += '</tr>';
					if (driver) {
						markerData += `<tr>
                              <td class="marker-data-caption">${Template7.global.IS_MARINE ? LANGUAGE.ASSET_EDIT_MSG24 : LANGUAGE.ASSET_EDIT_MSG23}</td>
                              <td class="marker-data-value">${driver.FirstName} ${driver.SubName}</td>
                          </tr>`;
					}

					if (self.data.CustomerType === 2 || self.data.CustomerType === 6) {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.ASSET_LIST_MSG22 + '</td>';
						markerData += '<td class="marker-data-value">' + asset.StockNumber + '</td>';
						markerData += '</tr>';
					}

					if (asset.PRDTName != '4G QT LTE Long Life' && asset.PRDTName != '4G QT LTE LONG LIFE' && asset.PRDTName != '4G QT LTE 200 Temp' && asset.PRDTName != '4G QT LTE 100') {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG002 + '</td>';
						markerData += '<td class="marker-data-value">'
							+ self.methods.capitalize(assetFeaturesStatus.status.value);
						if (assetFeaturesStatus.stopped) {
							markerData += '(' + assetFeaturesStatus.stopped.duration + ')';
						}
						markerData += '</td>';
						markerData += '</tr>';
					}
					markerData += '<tr>';
					let posType = asset.posInfo.positionType == 2 ? 'LBS' : 'GPS' + '(' + asset.posInfo.satelliteSignal + ')'
					let updType = asset.posInfo.positionType == 4 ? 'Iridium' : 'GPRS' + '(' + asset.posInfo.gsmSignal+ ')'
					markerData += `<td class="marker-data-caption">Update time <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 popover-open" style="cursor:pointer" data-popover=".popover-about"></i></td>
						<div class="popover popover-about">
						  <div class="popover-inner">
							<div class="block">
							  <p>Position Type: ${posType}</p>
							  <p>Update Type: ${updType}</p>
							</div>
						  </div>
						</div>`;
					markerData += '<td class="marker-data-value">' + asset.posInfo.sysTime.format(window.COM_TIMEFORMAT) + '</td>';
					markerData += '</tr>';
					markerData += '<tr>';
					markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG003 + '</td>';
					markerData += '<td class="marker-data-value">' + asset.posInfo.positionTime.format(window.COM_TIMEFORMAT) + '</td>';
					markerData += '</tr>';

					//console.log(asset.Input1Name)
					if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Input1) > 0 && ((asset.Input1Name && asset.Input1Name !== "NONE") || assetFeaturesStatus.installation.input1name.state == 'state-3')) {
						let installationOptionsInput1 = Protocol.Helper.getInstallationOptionsInput1();
						let option = installationOptionsInput1.find(itm => itm.value === asset.Input1Name)
						//if (option && option.name && option.icon) {
						markerData += `<tr>
                                              <td class="marker-data-caption">${asset.Input1Name ? asset.Input1Name : 'Input1'} </td>
                                              <td class="marker-data-value "><i class="f7-icons size-13 margin-right-8 icon-input-car-alarm ${assetFeaturesStatus.installation.input1name.state}"></i></td>
                                            </tr>`;
						//}
					} else if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Input1) > 0) {
						markerData += `<tr>
										  <td class="marker-data-caption">Input1  </td>
										  <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-car-alarm state-0"></i></td>
										</tr>`;
					}
					if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Input2) > 0 && ((asset.Input2Name && asset.Input2Name !== "NONE") || assetFeaturesStatus.installation.input2name.state == 'state-3')) {
						let installationOptionsInput2 = Protocol.Helper.getInstallationOptionsInput2();
						let option = installationOptionsInput2.find(itm => itm.value === asset.Input2Name)
						//if (option && option.name && option.icon) {
						markerData += `<tr>
                                              <td class="marker-data-caption">${asset.Input2Name ? asset.Input2Name : 'Input2'}  </td>
                                              <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-car-alarm ${assetFeaturesStatus.installation.input2name.state}"></i></td>
                                            </tr>`;
						//}
					} else if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Input2) > 0) {
						markerData += `<tr>
										  <td class="marker-data-caption">Input2  </td>
										  <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-car-alarm state-0"></i></td>
										</tr>`;
					}


					//if (asset.PRDTName == '4G QT LTE 200 Temp' || asset.PRDTName == '4G QT LTE 100') {
						if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Input3) > 0 && ((asset.Input3Name && asset.Input3Name !== "NONE") || assetFeaturesStatus.installation.input3name.state == 'state-3')) {
							let installationOptionsInput3 = Protocol.Helper.getInstallationOptionsInput3();
							let option = installationOptionsInput3.find(itm => itm.value === asset.Input3Name)
							//if (option && option.name && option.icon) {
							markerData += `<tr>
                                              <td class="marker-data-caption">${asset.Input3Name ? asset.Input3Name : 'Input3'}  </td>
                                              <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-car-alarm ${assetFeaturesStatus.installation.input3name.state}"></i></td>
                                            </tr>`;
							//}
						} else if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Input3) > 0) {
							markerData += `<tr>
                                              <td class="marker-data-caption">Input3  </td>
                                              <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-car-alarm state-0"></i></td>
                                            </tr>`;
						}
						if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Output1) > 0 && ((asset.Output1Name && asset.Output1Name !== "NONE") || assetFeaturesStatus.installation.output1name.state == 'state-4')) {
							let installationOptionsOutput1 = Protocol.Helper.getInstallationOptionsOutput1();
							let option = installationOptionsOutput1.find(itm => itm.value === asset.Output1Name)
							//if (option && option.name && option.icon) {
							markerData += `<tr>
                                              <td class="marker-data-caption">${asset.Output1Name  ? asset.Output1Name : 'Output1'}  </td>
                                              <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-ve-negative ${assetFeaturesStatus.installation.output1name.state}"></i></td>
                                            </tr>`;
							//}
						} else if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Output1) > 0)  {
							markerData += `<tr>
                                              <td class="marker-data-caption">Output1  </td>
                                              <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-ve-negative state-0"></i></td>
                                            </tr>`;
						}
						if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Output2) > 0 && ((asset.Output2Name && asset.Output2Name !== "NONE") || assetFeaturesStatus.installation.output2name.state == 'state-4')) {
							let installationOptionsOutput2 = Protocol.Helper.getInstallationOptionsOutput2();
							let option = installationOptionsOutput2.find(itm => itm.value === asset.Output2Name)
							//if (option && option.name && option.icon) {
							markerData += `<tr>
                                              <td class="marker-data-caption">${asset.Output2Name ? asset.Output2Name : 'Output2'}  </td>
                                              <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-ve-negative ${assetFeaturesStatus.installation.output2name.state}"></i></td>
                                            </tr>`;
							//}
						} else if ((asset.PRDTFeatures & Protocol.ProductInputFeatures.Output2) > 0) {
							markerData += `<tr>
                                              <td class="marker-data-caption">Output2  </td>
                                              <td class="marker-data-value"><i class="f7-icons size-13 margin-right-8 icon-input-ve-negative state-0"></i></td>
                                            </tr>`;
						}
					//}




					if (asset.posInfo.temp1 > 0) {
						markerData += `<tr>
										  <td class="marker-data-caption">Temp  </td>
										  <td class="marker-data-value">`
						if (asset.posInfo.temp1) markerData += asset.posInfo.temp1 + '&nbsp; °C '
						if (asset.posInfo.temp2) markerData += asset.posInfo.temp2 + '&nbsp; °C '
						if (asset.posInfo.temp3) markerData += asset.posInfo.temp3 + '&nbsp; °C '
						if (asset.posInfo.temp4) markerData += asset.posInfo.temp4 + '&nbsp; °C '
						if (asset.posInfo.temp5) markerData += asset.posInfo.temp5 + '&nbsp; °C '
						if (asset.posInfo.temp6) markerData += asset.posInfo.temp6 + '&nbsp; °C '
						if (asset.posInfo.temp7) markerData += asset.posInfo.temp7 + '&nbsp; °C '
						if (asset.posInfo.temp8) markerData += asset.posInfo.temp8 + '&nbsp; °C '

						markerData += `  </td>
										</tr>`;
					}

					if ((asset.PRDTFeatures & Protocol.ProductFeatures.Mileage) > 0) {
					
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG004 + '</td>';
						markerData += '<td class="marker-data-value">' + mileage + '</td>';
						markerData += '</tr>';
					}
					if (launchHours && asset.PRDTName != '4G QT LTE 200 Temp') {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG019 + '</td>';
						markerData += '<td class="marker-data-value">' + launchHours + '</td>';
						markerData += '</tr>';
					}
					if (assetFeaturesStatus.speed && (asset.PRDTFeatures & Protocol.ProductFeatures.Speed) > 0) {//asset.PRDTName != '4G QT LTE 200 Temp'
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG005 + '</td>';
						markerData += '<td class="marker-data-value">' + speed + '</td>';
						markerData += '</tr>';
					}
					if (assetFeaturesStatus.acc && (asset.PRDTFeatures & Protocol.ProductFeatures.Acc) > 0) {// && asset.PRDTName != '4G QT LTE 200 Temp'
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG006 + '</td>';
						markerData += '<td class="marker-data-value">' + assetFeaturesStatus.acc.value + '</td>';
						markerData += '</tr>';
					}
					if (assetFeaturesStatus.voltage && (asset.PRDTFeatures & Protocol.ProductFeatures.Voltage) > 0) {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG024 + '</td>';
						markerData += '<td class="marker-data-value">' + assetFeaturesStatus.voltage.value + '</td>';
						markerData += '</tr>';
					}
					if (assetFeaturesStatus.battery && (asset.PRDTFeatures & Protocol.ProductFeatures.Battery) > 0) {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG007 + '</td>';
						markerData += '<td class="marker-data-value">' + assetFeaturesStatus.battery.value + '</td>';
						markerData += '</tr>';
					}
					if (assetFeaturesStatus.power) {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG008 + '</td>';
						markerData += '<td class="marker-data-value">' + assetFeaturesStatus.power.value + '</td>';
						markerData += '</tr>';
					}
					if (assetFeaturesStatus.fuel && (asset.PRDTFeatures & Protocol.ProductFeatures.FuelSensor) > 0) {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG009 + '</td>';
						markerData += '<td class="marker-data-value">' + assetFeaturesStatus.fuel.value + '</td>';
						markerData += '</tr>';
					}
					if ( (asset.PRDTFeatures & Protocol.ProductFeatures.Direct) > 0) {//asset.PRDTName != '4G QT LTE 200 Temp'
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG010 + '</td>';
						markerData += '<td class="marker-data-value">' + deirectionCardinal + ' (' + asset.posInfo.direct + '&deg;)</td>';
						markerData += '</tr>';
					}
					if (positionType) {
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG013 + '</td>';
						markerData += '<td class="marker-data-value ">' + positionType + '</td>';
						markerData += '</tr>';
					}
					
					if ( (asset.PRDTFeatures & Protocol.ProductFeatures.LatLng) > 0) {//asset.PRDTName != '4G QT LTE 200 Temp'
						
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG011 + '</td>';
						markerData += '<td class="marker-data-value ">' + Protocol.Helper.convertDMS(asset.posInfo.lat, asset.posInfo.lng) + '</td>';
						markerData += '</tr>';
						markerData += '<tr>';
						markerData += '<td class="marker-data-caption">' + LANGUAGE.HOME_MSG012 + '</td>';
						markerData += '<td class="marker-data-value address-' + asset.IMEI + '">' + customAddress + '</td>';
						markerData += '</tr>';
					}
					markerData += '</table>';
					markerData += `
                           <p class="row">
                            <button class="col button button-fill button-small color-green" onclick="app.methods.showAssetAlarmsPopup('${asset.IMEI}')">${LANGUAGE.HOME_MSG046}</button>
                          </p>
                    `;
				}
			}

			return markerData;
		},
		showAssetAlarmsPopup: function (imei) {
			this.popup.open('.popup-additional-info');
			additionalInfoView.router.navigate({
				name: 'asset-log-last-alarms',
				query: { imei: imei },
			});
		},
		showAssetNetwork: function (imei) {
			//
		},
		showAdsPopup: function (title, message, filelink, link1, link2, link3, link1Name, link2Name, link3Name) {
			this.popup.open('.popup-ads-info');
			adsInfoView.router.navigate({
				name: 'ads',
				query: { title, message, filelink, link1, link2, link3, link1Name, link2Name, link3Name },
			});
		},
		showSnapShotsPopup: function (imei) {
			snapShotsPopup.open();
		},
		showPhotoEventsPopup: function (imei) {
			photoEventsPopup.open();
		},
		showVideoEventsPopup: function (imei) {
			videoEventsPopup.open();
		},
		showVideoLoopsPopup: function (imei) {
			videoLoopsPopup.open();
		},
		
		getAssetsWithMissingParam: function (missedParam) {
			let self = this;
			let ret = [];
			if (!missedParam) {
				return ret;
			}

			let assetList = self.methods.getFromStorage('assetList');
			let groupList = self.methods.getFromStorage('groupList');
			let keys = Object.keys(assetList);
			if (typeof missedParam === 'string') {
				for (const key of keys) {
					if (assetList[key].SolutionType && !assetList[key][missedParam]) {
						let obj = {
							IMEI: assetList[key].IMEI,
							Name: assetList[key].Name,
							StockNumber: assetList[key].StockNumber,
							Make: assetList[key].Describe1,
							Model: assetList[key].Describe2,
							Color: assetList[key].Describe3,
							Year: assetList[key].Describe4
						};
						if (assetList[key].GroupCode) {
							let groupIndex = groupList.findIndex(el => el.Code === assetList[key].GroupCode);
							if (groupIndex !== -1) {
								obj.GroupName = groupList[groupIndex].Name;
							}
						}
						ret.push(obj);
					}
				}
			}
			/*if (Array.isArray(missedParam)){
					  for (let i = 0; i < missedParam.length; i++) {
						  for (const key of keys) {
							  if (assetList[key].SolutionType && !assetList[key][missedParam[i]]){
								  ret.push(assetList[key]);
							  }
						  }
					  }
				  }*/

			return ret;
		},
		getAssetsListByCriteria: function (criteria) {
			let self = this;
			let ret = [];
			if (!criteria) {
				return ret;
			}

			let assetList = self.methods.getFromStorage('assetList');
			let groupList = self.methods.getFromStorage('groupList');
			let keys = Object.keys(assetList);

			switch (criteria) {
				case 'installed':
					for (const key of keys) {
						if (assetList[key].SolutionType && assetList[key].SolutionType.toLowerCase() !== 'deactivate') {
							let obj = {
								IMEI: assetList[key].IMEI,
								Name: assetList[key].Name,
								StockNumber: assetList[key].StockNumber,
								Make: assetList[key].Describe1,
								Model: assetList[key].Describe2,
								Color: assetList[key].Describe3,
								Year: assetList[key].Describe4,
								ActivationTime: assetList[key].ActivationTime
							};
							if (assetList[key].GroupCode) {
								let groupIndex = groupList.findIndex(el => el.Code === assetList[key].GroupCode);
								if (groupIndex !== -1) {
									obj.GroupName = groupList[groupIndex].Name;
								}
							}
							ret.push(obj);
						}
					}
					break;

				case 'deactivated':
					for (const key of keys) {
						if (assetList[key].SolutionType && assetList[key].SolutionType.toLowerCase() === 'deactivate') {
							let obj = {
								IMEI: assetList[key].IMEI,
								Name: assetList[key].Name,
								StockNumber: assetList[key].StockNumber,
								Make: assetList[key].Describe1,
								Model: assetList[key].Describe2,
								Color: assetList[key].Describe3,
								Year: assetList[key].Describe4,
								ActivationTime: assetList[key].ActivationTime
							};
							/*if (assetList[key].GroupCode){
											  let groupIndex = groupList.findIndex(el => el.Code === assetList[key].GroupCode);
											  if(groupIndex !== -1){
												  obj.GroupName = groupList[groupIndex].Name;
											  }
										  }*/
							ret.push(obj);
						}
					}
					break;

				case 'inInventory':
					for (const key of keys) {
						if (!assetList[key].SolutionType) {
							let obj = {
								IMEI: assetList[key].IMEI,
								Name: assetList[key].Name,
								StockNumber: assetList[key].StockNumber
							};
							if (assetList[key].GroupCode) {
								let groupIndex = groupList.findIndex(el => el.Code === assetList[key].GroupCode);
								if (groupIndex !== -1) {
									obj.GroupName = groupList[groupIndex].Name;
								}
							}
							ret.push(obj);
						}
					}
					break;
			}

			return ret;
		},

		getAssetImg: function (params, imgFor) {
			var assetImg = '';
			var pattern = /^IMEI_/i;
			var pattern2 = 'ic_';
			var regex = /_/gi;
			var regex2 = /\.[^/.]+$/; //remnove extension (.png, .jpg etc)
			var splitted = '';

			if (params && imgFor.assetList) {
				if (params.Icon && pattern.test(params.Icon)) {
					assetImg = '<img class="item_asset_img" src="https://upload.quiktrak.co/Attachment/images/' + params.Icon + '?' + new Date().getTime() + 'alt="">';
				} else if (params.Icon && params.Icon.substring(0, 3) == pattern2) {
					assetImg = '<div class="item_asset_img ' + Template7.global.DEALER_BG_COLOR_CLASS + '"><div class="text-align-center vertical-center size-28 "><i class="icon text-color-white asset-icon-' + params.Icon.replace(regex, '-').replace(regex2, '') + '"></i></div></div>';

				} else if (params.Name) {
					params.Name = $.trim(params.Name);
					splitted = params.Name.split(' ');
					if (splitted.length > 1) {
						var one = '';
						var two = '';
						for (var i = 0; i < splitted.length; i++) {
							if (splitted[i] && splitted[i][0]) {
								if (!one || !two) {
									if (!one) {
										one = splitted[i][0];
									} else {
										two = splitted[i][0];
										break;
									}
								}
							}
						}
						assetImg = '<div class="item_asset_img ' + Template7.global.DEALER_BG_COLOR_CLASS + '"><div class="text-align-center vertical-center size-18 text-color-white">' + one + two + '</div></div>';
					} else {
						assetImg = '<div class="item_asset_img ' + Template7.global.DEALER_BG_COLOR_CLASS + '"><div class="text-align-center vertical-center size-18 text-color-white">' + params.Name[0] + params.Name[1] + '</div></div>';
					}

				} else if (params.IMEI) {
					assetImg = '<div class="item_asset_img ' + Template7.global.DEALER_BG_COLOR_CLASS + '"><div class="text-align-center vertical-center size-18 text-color-white">' + params.IMEI[0] + params.IMEI[1] + '</div></div>';
				}
			} else if (params && imgFor.assetEdit) {
				if (params.Icon && pattern.test(params.Icon)) {
					assetImg = '<div class="top-asset-img vertical-center"> <img class="item_asset_img" data-name="' + params.Icon + '" src="https://upload.quiktrak.co/Attachment/images/' + params.Icon + '?' + new Date().getTime() + '" alt=""></div>';
				} else if (params.Icon && params.Icon.substring(0, 3) == pattern2) {
					assetImg = '<div class="top-asset-img vertical-center ' + Template7.global.DEALER_BG_COLOR_CLASS + '"><div class="item_asset_img text-align-center"><i class="icon size-75 text-color-white asset-icon-' + params.Icon.replace(regex, '-').replace(regex2, '') + '"></i></div></div>';
				} else {
					assetImg = false;
				}

			} else {
				assetImg = false;
			}
			//console.log(assetImg);
			return assetImg;
		},
		getGroupImg: function (params) {
			var ret = '';
			if (params && params.Name) {
				ret = '<div class="item_asset_img ' + Template7.global.DEALER_BG_COLOR_CLASS + '"><div class="text-align-center vertical-center size-18 text-color-white">' + params.Name[0].toUpperCase() + '</div></div>';
			} else {
				ret = '<div class="item_asset_img ' + Template7.global.DEALER_BG_COLOR_CLASS + '"><div class="text-align-center vertical-center size-18 text-color-white">G</div></div>';
			}
			return ret;
		},
		updateUserCredits: function (credits) {
			$$('#app .creditCount').html(credits);
		},

		checkBalance: function (alert) {
			var self = this;
			var userInfo = self.methods.getFromStorage('userInfo');
			var data = {
				MajorToken: userInfo.MajorToken,
				MinorToken: userInfo.MinorToken,
			};
			app.progressbar.show();
			app.request.get(API_URL.GET_BALANCE, data, function (result, xhr, status) {
				if (result && result.MajorCode == '000') {
					userInfo.UserInfo.SMSTimes = result.Data.SMSTimes;
					self.methods.setInStorage({ name: 'userInfo', data: userInfo });
					self.methods.updateUserCredits(result.Data.SMSTimes);
					if (alert) {
						app.methods.customDialog({ text: LANGUAGE.COM_MSG04 + ': ' + result.Data.SMSTimes });
					}
				}
				app.progressbar.hide();
			},
				function (xhr, status) {
					app.progressbar.hide();
					app.dialog.alert(LANGUAGE.COM_MSG07);
				},
				'json');
		},
		getAssetsByGroups: function (params = {}) {
			var self = this;

			var groupList = self.methods.getFromStorage('groupList');

			var assetList = self.methods.getFromStorage('assetList');
			var newAssetlist = [];

			if (assetList && !self.methods.isObjEmpty(assetList)) {
				/*creating temprorary empty obj for sorting groups*/
				var tempObjects = {
					'000000': {
						Name: LANGUAGE.ASSET_GROUPS_MSG11, //'Not in Group'
						Code: '000000',
						Assets: [],
					}
				};
				for (var i = groupList.length - 1; i >= 0; i--) {
					tempObjects[groupList[i].Code] = {
						Name: groupList[i].Name,
						Code: groupList[i].Code,
						Assets: [],
					};
				}

				/*sorting asset by adding into corresponding object*/
				$.each(assetList, function (key, val) {
					if (val.GroupCode && tempObjects[val.GroupCode]) {
						tempObjects[val.GroupCode].Assets.push(val);
					} else {
						tempObjects['000000'].Assets.push(val);
					}
				});

				/*creaiting one array with groups and assets*/
				$.each(tempObjects, function (key, val) {
					/*sorting in alphabet order*/
					if (val.Assets && val.Assets.length) {
						val.Assets.sort(function (a, b) {
							if (a.Name < b.Name) return -1;
							if (a.Name > b.Name) return 1;
							return 0;
						});
						newAssetlist.push(val);
					}
				});

				newAssetlist.sort(function (a, b) {
					if (a.Name < b.Name) return -1;
					if (a.Name > b.Name) return 1;
					return 0;
				});
				if (params.NoGroupToBottom) {
					/*move not assigned asset to the bottom*/
					newAssetlist.push(newAssetlist.splice(newAssetlist.findIndex(x => x.Code == '000000'), 1)[0]);
				} else {
					/*move not assigned asset to the top*/
					newAssetlist.unshift(newAssetlist.splice(newAssetlist.findIndex(x => x.Code == '000000'), 1)[0]);
				}
			}

			return newAssetlist;
		},
		getGroupNamesList: function () {
			let self = this;

			let ret = [];
			let groupList = app.methods.getFromStorage('groupList');
			if (groupList && groupList.length) {
				let keys = Object.keys(groupList);
				for (const key of keys) {
					ret.push(groupList[key]);
				}

				ret.sort(function (a, b) {
					if (a.Name < b.Name) return -1;
					if (a.Name > b.Name) return 1;
					return 0;
				});

				let indexNotInGroup = ret.findIndex(x => x.Code == '000000');
				if (indexNotInGroup > -1) {
					ret.splice(indexNotInGroup, 1);
				}
			}
			ret.unshift({
				Code: '000',
				Name: 'All',
			})
			return ret;
		},
		sortContactList: function (list) {
			var self = this;
			if (list && list.length) {
				for (var i = list.length - 1; i >= 0; i--) {
					list[i].FullName = list[i].FirstName + ' ' + list[i].SubName;
					list[i].FullName.trim();
				}
				list.sort(function (a, b) {
					if (a.FullName.toLowerCase() < b.FullName.toLowerCase()) return -1;
					if (a.FullName.toLowerCase() > b.FullName.toLowerCase()) return 1;
					return 0;
				});
			}
			return list;
		},
		sendCommandDeactivate: function (imei) {
			var self = this;

			if (imei) {
				/*let modalTex = `
							<div class="custom-modal-text">${ LANGUAGE.PROMPT_MSG0112 } <b>${ imei }</b>  ${ LANGUAGE.PROMPT_MSG0128 }</div>
							<div class="list no-hairlines margin-top-half no-margin-bottom">
								<ul>
									<li>
										<label class="item-checkbox item-content no-padding-left">
											<input type="checkbox" name="checkbox-in-inventory" value="" />
											<i class="icon icon-checkbox"></i>
											<div class="item-inner no-padding-right">
												<div class="item-title text-color-gray">${ LANGUAGE.ASSET_LIST_MSG39 }</div>
											</div>
										</label>
									</li>
								</ul>
							</div>`;*/
				let modalTex = `
                    <div class="custom-modal-text">${LANGUAGE.PROMPT_MSG0112} <b>${imei}</b>  ${LANGUAGE.PROMPT_MSG0128}</div>
                    <div class="list media-list no-hairlines no-hairlines-between no-margin">
                      <ul>
                        <li>
                          <label class="item-radio item-content no-padding">
                            <input type="radio" name="deactivate-radio" value="deactivate" checked="checked">
                            <div class="item-media">
                              <i class="icon icon-radio"></i>
                            </div>
                            <div class="item-inner no-margin padding-vertical-half no-padding-right no-padding-left">
                              <div class="item-title text-color-black">${LANGUAGE.COM_MSG130}</div>
                              <div class="item-text size-12 line-height-14">${LANGUAGE.PROMPT_MSG0129}</div>
                            </div>
                          </label>
                        </li> 
                        
                        <li>
                          <label class="item-radio item-content no-padding">
                            <input type="radio" name="deactivate-radio" value="terminate">
                            <div class="item-media">
                              <i class="icon icon-radio"></i>
                            </div>
                            <div class="item-inner no-margin padding-vertical-half no-padding-right no-padding-left">
                              <div class="item-title text-color-black">${LANGUAGE.COM_MSG132}</div>
                               <div class="item-text size-12 line-height-14">${LANGUAGE.PROMPT_MSG0131}</div>
                            </div>
                          </label>
                        </li>
                      </ul>
                    </div>`;
					/*<li>
                          <label class="item-radio item-content no-padding">
                            <input type="radio" name="deactivate-radio" value="stock">
                            <div class="item-media">
                              <i class="icon icon-radio"></i>
                            </div>
                            <div class="item-inner no-margin padding-vertical-half no-padding-right no-padding-left">
                              <div class="item-title text-color-black">${LANGUAGE.COM_MSG131}</div>
                               <div class="item-text size-12 line-height-14">${LANGUAGE.PROMPT_MSG0130}</div>
                            </div>
                          </label>
                        </li>*/

				self.dialog.create({
					//title: '<div class="custom-modal-logo-wrapper"><img class="custom-modal-logo" src="'+ self.data.AppDetails.logoModal +'" alt=""/></div>',
					title: `<span class="text-color-red">${LANGUAGE.COM_MSG133}</span>`,
					text: modalTex,
					buttons: [
						{
							text: LANGUAGE.COM_MSG01,
							cssClass: 'color-black',
						},
						{
							text: LANGUAGE.COM_MSG12,
							bold: true,
							cssClass: 'color-red',
							onClick: function (parent) {
								let type = parent.$el.find('input[name="deactivate-radio"]').val();

								var userInfo = self.methods.getFromStorage('userInfo');
								var data = {
									MinorToken: userInfo.MinorToken,
									MajorToken: userInfo.MajorToken,
									IMEI: imei,
									type: !type ? 'deactivate' : type
								};
								/*if(checkboxState){
													data.isInit = checkboxState
												}*/
								//console.log(data)
								self.preloader.show();
								self.request.post(API_URL.ASSET_DEACTIVATE, data, function (result, xhr, status) {
									self.preloader.hide();
									if (result && result.MajorCode == '000') {
										self.methods.customDialog({ title: imei, text: LANGUAGE.PROMPT_MSG0113 });

									} else if (result && result.MajorCode == '100' && result.MinorCode == '1003') {
										self.preloader.hide();
										self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
									} else {
										self.dialog.alert('Something wrong');
									}

								},
									function (xhr, status) {
										self.preloader.hide();
										self.dialog.alert('Error occured at sendCommandDeactivate');
									},
									'json');
							}
						},
					],
				}).open();
			}
		},
		sendCommandStatus: function (imsis) {
			var self = this;

			if (imsis) {
				var userInfo = self.methods.getFromStorage('userInfo');
					var data = {
					MajorToken: userInfo.MajorToken,
					MinorToken: userInfo.MinorToken,
					/*appToken: self.id,
					imsis: imsis,*/
					IMEI: imsis,
					SMSType: 'Query_Status',
				};
				//console.log(data);
				self.progressbar.show();
				self.request.post(API_URL.URL_SEND_SMS_BY_TYPE_VIA_TCP, data, function (result, xhr, status){
					self.utils.nextFrame(() => {
						app.progressbar.hide();
					});

					if (result && result.MajorCode == '000') {
						self.methods.customNotification({ title: LANGUAGE.PROMPT_MSG017 });
						self.methods.checkBalance();
					} else if (result && result.MajorCode == '200' && result.MinorCode == '1003') {
						self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
					} else if (result && result.MajorCode == '100' && result.MinorCode == '1003') {
						self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
					} else {
						self.dialog.alert('Something wrong');
						//self.methods.customDialogNoCredit();
					}
				},
					function (xhr, status) {
						self.utils.nextFrame(() => {
							app.progressbar.hide();
							app.dialog.alert(LANGUAGE.COM_MSG07);
						});
					},
					'json');
			} else {
				self.methods.customDialog(LANGUAGE.PROMPT_MSG027);
			}

		},
		sendCommandIButton: function(selectedRadio, imsi) {
			var self = this;
			var code = ""
			if(selectedRadio == 'remove-all') {
				code = "CUS_de52ef97_e5eb_4817_ab1f_80d9eaa4a828"	
			} else if(selectedRadio == 'immobiliser-on') {
				code = "CUS_bc8778ff_a674_4c40_a745_7baac9426096"	
			} else if (selectedRadio == 'immobiliser-off') {
				code = "CUS_caab463a_54a0_4618_b599_8710151ef675"
			}
			var data = {
				/*MinorToken: userInfo.MinorToken,
				appToken: self.id,
				imsis: imsis,*/
				IMSI: imsi,
				SMSType: code,
			};

			console.log(selectedRadio, imsi)
			if (imsi) {
				self.progressbar.show();
				self.request.post(API_URL.URL_SEND_SMS_BY_TYPE, data, function (result, xhr, status){
					self.utils.nextFrame(() => {
						app.progressbar.hide();
					});

					if (result && result.MajorCode == '000') {
						//self.methods.customNotification({ title: LANGUAGE.PROMPT_MSG017 });
						//self.methods.checkBalance();
					} else if (result && result.MajorCode == '200' && result.MinorCode == '1003') {
					//	self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
					} else if (result && result.MajorCode == '100' && result.MinorCode == '1003') {
					//	self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
					} else {
						//self.dialog.alert('Something wrong');
					//	self.methods.customDialogNoCredit();
					}
				},
					function (xhr, status) {
						self.utils.nextFrame(() => {
							app.progressbar.hide();
							app.dialog.alert(LANGUAGE.COM_MSG07);
						});
					},
					'json');
			} else {
				self.methods.customDialog(LANGUAGE.PROMPT_MSG027);
			}
		},
		resetAsset: function (imei) {
			var self = this;

			var userInfo = self.methods.getFromStorage('userInfo');

			var data = {
				MinorToken: userInfo.MinorToken,
				MajorToken: userInfo.MajorToken,
				IMEI: imei,
			};


			self.dialog.create({
				title: 'Reset',
				verticalButtons: true,
				closeByBackdropClick: true,
				buttons: [
					{
						text:'Mileage',
						//bold: true,
						onClick: function () {
							self.dialog.confirm('The value will be reset to zero', function () {
								self.progressbar.show();
								self.request.post(API_URL.RESET_MILEAGE, data, function (result, xhr, status) {
									self.utils.nextFrame(() => {
										app.progressbar.hide();
									});
									if (result) {
										self.dialog.alert('Reset successfully.');
									 
										self.methods.getNewAssetsData(); 
									} else {
										self.dialog.alert('Something wrong');
										return
									}
								})
							 // '1' - means update

							  });
							
						}
					},
					{
						text:'Launch Hours',
						//bold: true,
						onClick: function () {
							self.dialog.confirm('The value will be reset to zero', function () {
								self.progressbar.show();
								self.request.post(API_URL.RESET_HOURS, data, function (result, xhr, status) {
									self.utils.nextFrame(() => {
										app.progressbar.hide();
									});
									if (result) {
										self.dialog.alert('Reset successfully. Please refresh page');
									} else {
										self.dialog.alert('Something wrong');
										return
									}
								})
							});
						
						}
					},
					{
						text:'History',
						//bold: true,
						onClick: function () {
							self.dialog.confirm('The value will be reset to zero', function () {
								self.progressbar.show();
								self.request.post(API_URL.RESET_HISTORY, data, function (result, xhr, status) {
									self.utils.nextFrame(() => {
										app.progressbar.hide();
									});
									if (result) {
										self.dialog.alert('Reset successfully. Please refresh page');
									} else {
										self.dialog.alert('Something wrong');
										return
									}
								}) 
							});
						
						}
					}


				],

			}).open();







		},
		sendCommandPosition: function (imsis) {
			var self = this;

			if (imsis) {
				var userInfo = self.methods.getFromStorage('userInfo');

				var data = {
					
					MajorToken: userInfo.MajorToken,
					MinorToken: userInfo.MinorToken,
					/*MinorToken: userInfo.MinorToken,
					appToken: self.id,
					imsis: imsis,*/
					IMEI: imsis,
					SMSType: 'Query_Position',
				};
				//console.log(data);
				self.progressbar.show();
				self.request.post(API_URL.URL_SEND_SMS_BY_TYPE_VIA_TCP, data, function (result, xhr, status) {
					self.utils.nextFrame(() => {
						app.progressbar.hide();
					});

					if (result && result.MajorCode == '000') {
						self.methods.customNotification({ title: LANGUAGE.PROMPT_MSG017 });
						self.methods.checkBalance();
					} else if (result && result.MajorCode == '200' && result.MinorCode == '1003') {
						self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
					} else if (result && result.MajorCode == '100' && result.MinorCode == '1003') {
						self.methods.customDialog({ title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051 });
					} else {
						self.dialog.alert('Something wrong');
						//self.methods.customDialogNoCredit();
					}
				},
					function (xhr, status) {
						self.utils.nextFrame(() => {
							app.progressbar.hide();
							app.dialog.alert(LANGUAGE.COM_MSG07);
						});

					},
					'json');
			} else {
				self.methods.customDialog(LANGUAGE.PROMPT_MSG027);
			}
		},
		commandMultipleConfirm: function (imsis, commandType) {
			var self = this;

			if (imsis && commandType) {
				var imsisArray = imsis.split(',');

				var text = LANGUAGE.PROMPT_MSG020 + '(' + imsisArray.length + '). ' + LANGUAGE.PROMPT_MSG021 + '(' + imsisArray.length + ' ' + LANGUAGE.COM_MSG03 + '). ' + LANGUAGE.PROMPT_MSG022;
				app.dialog.confirm(text,
					function () {
						if (commandType == 'position') {
							self.methods.sendCommandPosition(imsis);
						} else if (commandType == 'status') {
							self.methods.sendCommandStatus(imsis);
						}
					},
					function () {
						// cancel
					}
				);
			} else {
				self.methods.customDialog({ text: LANGUAGE.PROMPT_MSG023 });
			}
		},
		/*sendReportPlaybackOnEmail: function(data, callbackFunc){
				let self = this;
		
				self.preloader.show();
				self.request.postJSON(API_URL.GET_PLAYBACK_REPORT_ON_MAIL, data, function (result={}, xhr, status) {
						self.preloader.hide();
						console.log(result);
		
						//self.DynamicSendOnEmailPopup.close();
						callbackFunc();
						//self.methods.customNotification({text: LANGUAGE.PROMPT_MSG0109});
					},
					function (xhr, status) {
						self.preloader.hide();
		
						if (!xhr){
							self.dialog.alert('Error occured at Send Report on Email ');
							return;
						}
						switch (xhr.status) {
							case 202:
								//self.methods.customNotification({text: LANGUAGE.PROMPT_MSG0109});
								callbackFunc();
								//self.DynamicSendOnEmailPopup.close();
								break;
							case 204:
								self.methods.customDialog({title: LANGUAGE.ASSET_PLAYBACK_MSG00, text: LANGUAGE.COM_MSG35});
								break;
		
							default:
								if (xhr.response){
									let response = self.methods.isJsonString(xhr.response);
									if (response && response.code === 500){
										let messages = self.methods.isJsonString(response.message);
										if(messages && messages.length){
											for (let i = 0; i < messages.length; i++) {
												if (messages[i].MajorCode === '100' && messages[i].MinorCode === '1002'){
													self.methods.customDialog({title: Protocol.Helper.getReportTypeName(self.Type), text: LANGUAGE.PROMPT_MSG0111});
													return;
												}
											}
										}
									}
								}
								self.dialog.alert('Error occured at Send Report on Email ');
						}
					},
					'json');
				console.log(data);
			},*/
		sendReportPlaybackOnEmail: function (data, callbackFunc, errCallback) {
			let self = this;
var userInfo = app.methods.getFromStorage('userInfo');
			self.request.get(API_URL.REPORT_PLAYBACK_GENERATE, data,
				function (result) {
					//console.log(result)
					if (result.MajorCode !== '000' || !result.Data || !result.Data.FileToken) {
						self.dialog.alert(LANGUAGE.PROMPT_MSG0127 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}<br>${result.Data}`);
						errCallback()
						return
					}

					let checkTimer = 5000;
					let checkRetryMax = 10;
					let checkRetry = 0;
					let checkStatusEnum = {
						Unknown: 0,
						Processing: 1,
						Success: 2,
						Error: -1
					};

					let errFunc = function (err) {
						if (err) {
							self.dialog.alert(LANGUAGE.PROMPT_MSG0127 + `<br>MajorCode: ${result.MajorCode}<br>MinorCode: ${result.MinorCode}<br>${result.Data}`);
						} else {
							self.dialog.alert(LANGUAGE.PROMPT_MSG0121);
						}
						errCallback()
					};

					let checkReportPlaybackStatus = function (FileToken) {
						++checkRetry;

						self.methods.getReportPlaybackStatus(FileToken)
							.then(function (reportStatus) {
								switch (reportStatus) {
									case checkStatusEnum.Success:
										let parsedURLData = self.utils.parseUrlQuery(data.Url);
										//console.log(moment(parsedURLData.From), moment(parsedURLData.From).format(window.COM_TIMEFORMAT))
										self.methods.sendEmailWithPlayback({
											Logo: self.data.logoExternal,
											ReportName: LANGUAGE.PROMPT_MSG0136,
											DownloadLink: API_URL.REPORT_PLAYBACK_DOWNLOAD + '?FileToken=' + FileToken,
											//DateFrom: moment(parsedURLData.From).add(self.data.UTCOFFSET, 'minutes').format(window.COM_TIMEFORMAT),
											//DateTo: moment(parsedURLData.To).add(self.data.UTCOFFSET, 'minutes').format(window.COM_TIMEFORMAT),
											DateFrom: moment(parsedURLData.From).format(window.COM_TIMEFORMAT),
											DateTo: moment(parsedURLData.To).format(window.COM_TIMEFORMAT),
											EmailList: data.recipients,
										})
											.then(function () {
												self.preloader.hide();
												callbackFunc(API_URL.REPORT_PLAYBACK_DOWNLOAD + '?FileToken=' + FileToken)
											}, errFunc);
										break;
									case checkStatusEnum.Processing:
										if (checkRetry > checkRetryMax) {
											self.dialog.alert(LANGUAGE.PROMPT_MSG0121);
											errCallback()
										} else {
											setTimeout(function () {
												checkReportPlaybackStatus(FileToken)
											}, checkTimer)
										}
										break;
									default:
										self.dialog.alert(LANGUAGE.PROMPT_MSG0121);
										errCallback()
								}
							}, errFunc)
					}
					setTimeout(function () {
						checkReportPlaybackStatus(result.Data.FileToken)
					}, checkTimer)

				},
				function (err) {
					console.log(err);
					if (err && err.status === 404) {
						self.dialog.alert(LANGUAGE.PROMPT_MSG0120);
					} else {
						self.dialog.alert(LANGUAGE.COM_MSG07);
					}
					errCallback()
				},
				'json')

		},
		getReportPlaybackStatus: function (FileToken) {
			let self = this;
			return new Promise((resolve, reject) => {
				self.request.get(API_URL.REPORT_PLAYBACK_QUERY_STATE, { FileToken: FileToken },
					function (result) {
						if (result.MajorCode === '000' && result.Data) {
							resolve(result.Data.State)
						} else {
							reject(result)
						}
					},
					function (err) {
						console.log(err);
						if (err && err.status === 404) {
							self.dialog.alert(LANGUAGE.PROMPT_MSG0120);
						} else {
							self.dialog.alert(LANGUAGE.COM_MSG07);
						}
						reject()
					},
					'json')

			});
		},
		sendEmailWithPlayback: function (data) {
			let self = this;
			return new Promise((resolve, reject) => {
				self.request.post(API_URL.REPORT_PLAYBACK_SEND_EMAIL, data,
					function (result) {
						if (result.MajorCode === '000' && result.Data) {
							resolve(result.Data)
						} else {
							reject(result)
						}
					},
					function (err) {
						console.log(err);
						if (err && err.status === 404) {
							self.dialog.alert(LANGUAGE.PROMPT_MSG0120);
						} else {
							self.dialog.alert(LANGUAGE.COM_MSG07);
						}
						reject()
					},
					'json')
			});
		},
		getImsiForMultipleCommand: function (container) {
			var self = this;

			var imsis = $$(container).data('imsis');
			var commandType = $$(container).data('type');

			if (imsis) {
				self.methods.commandMultipleConfirm(imsis, commandType);
			} else {
				self.methods.customDialog({ text: LANGUAGE.PROMPT_MSG023 });
			}

		},
		copyToClipboard: function (text) {
			if (window.clipboardData && window.clipboardData.setData) {
				// Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
				return window.clipboardData.setData("Text", text);

			}
			else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
				var textarea = document.createElement("textarea");
				textarea.textContent = text;
				textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
				document.body.appendChild(textarea);
				textarea.select();
				try {
					return document.execCommand("copy");  // Security exception may be thrown by some browsers.
				}
				catch (ex) {
					console.warn("Copy to clipboard failed.", ex);
					return false;
				}
				finally {
					document.body.removeChild(textarea);
				}
			}
		},
		orderAssetList: function (container) {
			var self = this;
			if (container) {
				var orderBy = $$(container).find('input[type="radio"]').val();
				var virtualList = self.virtualList.get('.assetList');
				if (virtualList && virtualList.items && virtualList.items.length) {
					var assets = virtualList.items;

					if (orderBy != virtualList.$el.data('order-by')) {
						for (var i = assets.length - 1; i >= 0; i--) {
							if (assets[i].Assets && assets[i].Assets.length) {
								assets[i].Assets.reverse();
							}
						}
						virtualList.replaceAllItems(assets);
					}

					virtualList.$el.data('order-by', orderBy); // saving selected option, to show next time when popover will be opened again
				}
			}
		},
		sortAssetList: function (container) {
			var self = this;

			if (container) {
				var sortBy = $$(container).data('sort-by');
				var virtualList = self.virtualList.get('.assetList');
				var orderBy = virtualList.$el.data('order-by');

				if (virtualList && virtualList.items && virtualList.items.length) {
					var assets = virtualList.items;

					assets = self.methods.sortListByState(assets, sortBy);
					if (orderBy != 'asc') {
						for (var i = assets.length - 1; i >= 0; i--) {
							if (assets[i].Assets && assets[i].Assets.length) {
								assets[i].Assets.reverse();
							}
						}
					}
					virtualList.replaceAllItems(assets);

					//virtualList.$el.data('sort-by', sortBy); // saving selected option, to show next time when popover will be opened again
				}
			}
		},

		sortParseDatePhoto: function (data) {
			let dataObj = data;
			console.log('dataObj', data)
			let dateArr = [];
			for (let i = dataObj.length - 1; i >= 0; i--) {
				let dataArr = [];
				let filename = dataObj[i].Time;
				let time = filename;
				let newDate = dataObj[i].Time.split('T')[0]

				let index = dateArr.findIndex(item => item.title === newDate);

				if (index == -1) {
					dataArr.push(dataObj[i]);
					dateArr.push({
						title: newDate,
						data: dataArr
					});
				} else {
					dateArr[index].data.push(dataObj[i]);
				}
			}


			return dateArr;
		},
		
		sortParseDatePhotoAdd: function (data) {
			let dataObj = data;
			console.log('dataObj', data)
			let dateArr = [];
			for (let i = dataObj.length - 1; i >= 0; i--) {
				let dataArr = [];
				let filename = dataObj[i].fileTimeStr;
				let time = filename;
				let newDate = dataObj[i].fileTimeStr

				let index = dateArr.findIndex(item => item.title === newDate);

				if (index == -1) {
					dataArr.push(dataObj[i]);
					dateArr.push({
						title: newDate,
						data: dataArr
					});
				} else {
					dateArr[index].data.push(dataObj[i]);
				}
			}


			return dateArr;
		},
		
		sortTaskList: function (container) {
			var self = this;

			if (container) {
				var sortBy = $$(container).data('sort-by');
				var virtualList = self.virtualList.get('.taskList');
				//var orderBy = virtualList.$el.data('order-by');

				if (virtualList && virtualList.items && virtualList.items.length) {
					var tasks = virtualList.items;

					tasks = self.methods.sortListByState(tasks, sortBy);
				 
					virtualList.replaceAllItems(tasks);

					//virtualList.$el.data('sort-by', sortBy); // saving selected option, to show next time when popover will be opened again
				}
			}
		},
		filterAssetList: function (container) {
			var self = this;

			if (container) {
				var filterType = $$(container).find('input[type="radio"]').val();
				var virtualList = self.virtualList.get('.assetList');
				var orderBy = virtualList.$el.data('order-by');

				if (virtualList && virtualList.items && virtualList.items.length) {

					var filteredObj = self.methods.filterList(virtualList.items, filterType);
					if (orderBy != 'asc') {
						for (var i = filteredObj.list.length - 1; i >= 0; i--) {
							if (filteredObj.list[i].Assets && filteredObj.list[i].Assets.length) {
								filteredObj.list[i].Assets.reverse();
							}
						}
					}
					virtualList.replaceAllItems(filteredObj.list);
					if (filteredObj.itemIndexToShow && filteredObj.itemIndexToShow.length) {
						virtualList.filterItems(filteredObj.itemIndexToShow);
					}


					virtualList.$el.data('filter-type', filterType); // saving selected option, to show next time when popover will be opened again
				}


			}
		},
		sortListByState: function (list, sortBy, orderBy) {
			if (list && list.length) {
				//console.log(list);
				for (var i = list.length - 1; i >= 0; i--) {
					if (list[i] && list[i].Assets) {
						list[i].Assets.sort(function (a, b) {
							if (a.Name < b.Name) return -1;
							if (a.Name > b.Name) return 1;
							return 0;
						});

						switch (sortBy) {
							case 'state':
								var oneDay = 1000 * 60 * 60 * 24;
								var now = moment();
								var arrayOnline = [];
								var arrayOffline = [];
								for (var y = 0; y < list[i].Assets.length; y++) {
									if (POSINFOASSETLIST[list[i].Assets[y].IMEI] && POSINFOASSETLIST[list[i].Assets[y].IMEI].posInfo && POSINFOASSETLIST[list[i].Assets[y].IMEI].posInfo.positionTime) {
										var dateDifference = Protocol.Helper.getDifferenceBTtwoDates(POSINFOASSETLIST[list[i].Assets[y].IMEI].posInfo.positionTime, now);
										if (dateDifference <= oneDay) {
											arrayOnline.push(list[i].Assets[y]);
										} else {
											arrayOffline.push(list[i].Assets[y]);
										}
									} else {
										arrayOffline.push(list[i].Assets[y]);
									}
								}
								list[i].Assets = arrayOnline.concat(arrayOffline);

								break;

							case 'StockNumber': case 'Describe2': case 'Describe1': case 'Describe4': case 'Describe3': case 'DaysInInventory':
								list[i].Assets.sort(function (a, b) {
									if (a[sortBy] < b[sortBy]) return -1;
									if (a[sortBy] > b[sortBy]) return 1;
									return 0;
								});
								break;



						}
					}
				}

			}
			return list;
		},
		filterList: function (list, filterType) {
			var itemIndexToShow = [];
			if (list && list.length) {
				switch (filterType) {
					case 'loc8': case 'track': case 'watch':
						for (let i = list.length - 1; i >= 0; i--) {
							if (list[i] && list[i].Assets && list[i].Assets.length) {
								for (let y = list[i].Assets.length - 1; y >= 0; y--) {
									if (list[i].Assets[y].SolutionType && list[i].Assets[y].SolutionType.toLowerCase().indexOf(filterType) >= 0) {
										if (!itemIndexToShow.includes(i)) {
											itemIndexToShow.push(i);
										}
										list[i].Assets[y].hidden = false;
									} else {
										list[i].Assets[y].hidden = true;
									}
								}
							}
						}
						break;

					case 'protect': case 'qprotect': case 'witiprotect': case 'witiqprotect':
						for (let i = list.length - 1; i >= 0; i--) {
							if (list[i] && list[i].Assets && list[i].Assets.length) {
								for (let y = list[i].Assets.length - 1; y >= 0; y--) {
									if (list[i].Assets[y].SolutionType && list[i].Assets[y].SolutionType.toLowerCase().indexOf('protect') >= 0 ||
										list[i].Assets[y].SolutionType && list[i].Assets[y].SolutionType.toLowerCase().indexOf('qprotect') >= 0 ||
										list[i].Assets[y].SolutionType && list[i].Assets[y].SolutionType.toLowerCase().indexOf('witiprotect') >= 0 ||
										list[i].Assets[y].SolutionType && list[i].Assets[y].SolutionType.toLowerCase().indexOf('witiqprotect') >= 0) {
										if (!itemIndexToShow.includes(i)) {
											itemIndexToShow.push(i);
										}
										list[i].Assets[y].hidden = false;
									} else {
										list[i].Assets[y].hidden = true;
									}
								}
							}
						}
						break;

					case 'notinstalled':
						for (let i = list.length - 1; i >= 0; i--) {
							if (list[i] && list[i].Assets && list[i].Assets.length) {
								for (let y = list[i].Assets.length - 1; y >= 0; y--) {
									if (!list[i].Assets[y].SolutionType) {
										if (!itemIndexToShow.includes(i)) {
											itemIndexToShow.push(i);
										}
										list[i].Assets[y].hidden = false;
									} else {
										list[i].Assets[y].hidden = true;
									}
								}
							}
						}
						break;

					case 'installed':
						for (let i = list.length - 1; i >= 0; i--) {
							if (list[i] && list[i].Assets && list[i].Assets.length) {
								for (let y = list[i].Assets.length - 1; y >= 0; y--) {
									if (list[i].Assets[y].SolutionType) {
										if (!itemIndexToShow.includes(i)) {
											itemIndexToShow.push(i);
										}
										list[i].Assets[y].hidden = false;
									} else {
										list[i].Assets[y].hidden = true;
									}
								}
							}
						}
						break;

					default: //show all
						for (let i = list.length - 1; i >= 0; i--) {
							itemIndexToShow.push(i);
							if (list[i] && list[i].Assets && list[i].Assets.length) {
								for (let y = list[i].Assets.length - 1; y >= 0; y--) {
									list[i].Assets[y].hidden = false;
								}
							}
						}
				}
			}
			if (itemIndexToShow.length) {
				itemIndexToShow.reverse();
			}
			return { list, itemIndexToShow };
		},
		setStatusNewState: function (params) {
			if (params.state === true) {
				POSINFOASSETLIST[params.asset].StatusNew = POSINFOASSETLIST[params.asset].StatusNew | Protocol.StatusNewEnum[params.forAlarm];
			} else {
				POSINFOASSETLIST[params.asset].StatusNew = POSINFOASSETLIST[params.asset].StatusNew & ~Protocol.StatusNewEnum[params.forAlarm];
			}
		},
		getDashboardDataTableArray: function () {
			let assetArray = [];

			if (POSINFOASSETLIST) {
				let oneDay = 1000 * 60 * 60 * 24;
				let now = moment();
				const keys = Object.keys(POSINFOASSETLIST);
				for (const key of keys) {
					let asset = POSINFOASSETLIST[key];
					let assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(asset, { onlyNumber: true, inKilometers: true });
					let dateDifference = Protocol.Helper.getDifferenceBTtwoDates(asset.posInfo.positionTime, now);
					if (dateDifference <= oneDay) {
						/*assetArray.push({
										IMEI: asset.IMEI,
										AssetName: asset.Name,
										GroupCode: asset.GroupCode ? asset.GroupCode : '',
										Voltage: assetFeaturesStatus.voltage ? assetFeaturesStatus.voltage.value : '-',
										StationaryTime: assetFeaturesStatus.stopped ? assetFeaturesStatus.stopped.duration : '-',
										Milege: assetFeaturesStatus.mileage ? assetFeaturesStatus.mileage.value : '-',
										EngineHours: assetFeaturesStatus.engineHours ? assetFeaturesStatus.engineHours.value : '-',
										StockNumber: asset.StockNumber ? asset.StockNumber : '',
									});*/
						assetArray.push([
							asset.GroupCode ? asset.GroupCode : '',
							'',
							asset.Name,
							asset.StockNumber ? asset.StockNumber : '-',
							assetFeaturesStatus.voltage ? assetFeaturesStatus.voltage.value : '-',
							assetFeaturesStatus.stopped ? assetFeaturesStatus.stopped.duration : '-',
							assetFeaturesStatus.mileage ? assetFeaturesStatus.mileage.value : '-',
							assetFeaturesStatus.engineHours ? assetFeaturesStatus.engineHours.value : '-',
							'-', //fuel used
							{
								IMEI: asset.IMEI,
								AssetName: asset.Name,
								GroupCode: asset.GroupCode ? asset.GroupCode : '',
								Voltage: assetFeaturesStatus.voltage ? assetFeaturesStatus.voltage.value : '-',
								StationaryTime: assetFeaturesStatus.stopped ? assetFeaturesStatus.stopped.duration : '-',
								Mileage: assetFeaturesStatus.mileage ? assetFeaturesStatus.mileage.value : '-',
								EngineHours: assetFeaturesStatus.engineHours ? assetFeaturesStatus.engineHours.value : '-',
								StockNumber: asset.StockNumber ? asset.StockNumber : '-',
							}
						]);
					}
				}
			}

			return assetArray;
		},
		formatDashboardDataTableArray: function (array) {
			let assetArray = [];
			if (array && array.length) {
				for (let i = 0; i < array.length; i++) {
					let asset = POSINFOASSETLIST[array[i].IMEI];
					let assetFeaturesStatus = Protocol.Helper.getAssetStateInfo(asset, { onlyNumber: true, inKilometers: true });
					let engineHours = array[i].Idle + array[i].Move;
					let mileage = array[i].Mileage ? parseFloat(array[i].Mileage).toFixed(2) : '-';
					if (this.data.AppDetails.isMarine && array[i].Mileage) {
						mileage = Protocol.Helper.getMileageValue('KT', array[i].Mileage)
					}

					assetArray.push([
						asset.GroupCode ? asset.GroupCode : '',
						'',
						asset.Name,
						asset.StockNumber ? asset.StockNumber : '-',
						assetFeaturesStatus.voltage ? assetFeaturesStatus.voltage.value : '-',
						//TimeSpan(array[i].Stop * 1000).format('d[d] h[h] m[m]'),
						array[i].Stop ? moment.duration(array[i].Stop, "seconds").format('d[d] h[h] m[m]') : '-',
						array[i].Mileage ? mileage : '-',
						engineHours ? TimeSpan(engineHours * 1000).format("^hh:mm:ss") : '-',
						array[i].Fuel ? parseFloat(array[i].Fuel).toFixed(2) : '-',
						{
							IMEI: array[i].IMEI,
							AssetName: asset.Name,
							GroupCode: asset.GroupCode ? asset.GroupCode : '',
							StockNumber: asset.StockNumber ? asset.StockNumber : '-',
							Voltage: assetFeaturesStatus.voltage ? assetFeaturesStatus.voltage.value : '-',
							StationaryTime: array[i].Stop ? moment.duration(array[i].Stop, "seconds").format('d[d] h[h] m[m]') : '-',
							Mileage: array[i].Mileage ? mileage : '-',
							EngineHours: engineHours ? TimeSpan(engineHours * 1000).format("^hh:mm:ss") : '-',
							FuelUsed: array[i].Fuel ? parseFloat(array[i].Fuel).toFixed(2) : '-',
						}
					])
				}
			}
			return assetArray
		},
		/* customAlertOnDevelopment(params){
				//if (params ) {}
				//app.dialog.alert(LANGUAGE.PROMPT_MSG038, title);
			},*/
		showToast: function (text) {
			this.toast.create({
				position: 'center',
				text: text,
				closeTimeout: 1000,
				destroyOnClose: true,
			}).open();
		},
		customDialog: function (params) {
			var self = this;
			var modalTex = '';

			let buttons = [
				{
					text: LANGUAGE.COM_MSG12,
				},
			];
			if (params.title) {
				modalTex += '<div class="custom-modal-title text-color-red">' + params.title + '</div>';
			}
			if (params.text) {
				modalTex += '<div class="custom-modal-text">' + params.text + '</div>';
			}

			if (params.buttons) {
				buttons = params.buttons
			}

			if (params.vertical) {
				verticalButtons = true
			}
			self.dialog.create({
				title: !params.noLogo ? '<div class="custom-modal-logo-wrapper"><img class="custom-modal-logo" src="' + self.data.AppDetails.logoModal + '" alt=""/></div>' : '',
				text: modalTex,
				buttons: buttons,

			}).open();
		},
		customDialogNoCredit: function () {
			var modalTex = '<div class="custom-modal-title text-color-red">' + LANGUAGE.PROMPT_MSG047 + '</div>' +
				'<div class="custom-modal-text">' + LANGUAGE.PROMPT_MSG029 + '</div>';
			this.dialog.create({
				title: '<div class="custom-modal-logo-wrapper"><img class="custom-modal-logo" src="' + this.data.AppDetails.logoModal + '" alt=""/></div>',
				text: modalTex,
				buttons: [
					{
						text: LANGUAGE.COM_MSG14
					},
					{
						text: LANGUAGE.COM_MSG12,
						//bold: true,
						onClick: function () {
							leftView.router.navigate('/credit-recharge/');
						}
					},
				]
			}).open();
		},
		customNotification: function (params) {
			var self = this;
			self.notification.create({


				icon: '<img src="' + self.data.AppDetails.favicon + '" class="icon-notification" alt="" />',
				title: self.name,
				//titleRightText: 'now',
				subtitle: params.title ? params.title : '',
				text: params.text ? params.text : '',
				closeTimeout: params.hold ? params.hold : 3000,
				closeOnClick: true,
				//closeButton: true,
				on: {
					close: function (notification) {
						notification.$el.remove();
					}
				},

			}).open();
		},
		getTaskList: function (MajorToken) {
			let self = this;
			let url = API_URL.GET_TASKS + '?MajorToken=' + MajorToken
		 
			return new Promise((resolve, reject) => {
				self.request.get(url,
					function (result) {
					 
						if (result.MajorCode === '000') {
							self.methods.setInStorage({name: 'taskList', data: result.Data});
							if (result.Data?.length) {
							 
							}
							resolve(result.Data)
						}  
					},
					function (xhr, status) {
						console.log(xhr);
						console.log(status);
				 
					},
					'json');
			})
		},
		getCheckList: function (addUrlParams) {
			let self = this;

			self.preloader.show();
			return new Promise((resolve, reject) => {
				self.request.getJSON(API_URL.GET_CHECKLIST + addUrlParams,
					function (result) {
						self.preloader.hide();
						if (result.MajorCode === '000' && result.Data) {
						 
							resolve(result.Data)
						} else {
							reject(result)
						}
					},
					function (err) {
						console.log(err);
						if (err && err.status === 404) {
							self.dialog.alert(LANGUAGE.PROMPT_MSG0120);
						} else {
							self.dialog.alert(LANGUAGE.COM_MSG07);
						}
						reject()
					},
					'json')

			});
		},
		getTripsOfDriver: function (addUrlParams) {
			let self = this;

			self.preloader.show();
			return new Promise((resolve, reject) => {
				self.request.getJSON(API_URL.GET_TRIP_OF_DRIVER + addUrlParams,
					function (result) {
						self.preloader.hide();
						if (result.MajorCode === '000' && result.Data) {
						 
							resolve(result.Data)
						} else {
							reject(result)
						}
					},
					function (err) {
						console.log(err);
						if (err && err.status === 404) {
							self.dialog.alert(LANGUAGE.PROMPT_MSG0120);
						} else {
							self.dialog.alert(LANGUAGE.COM_MSG07);
						}
						reject()
					},
					'json')

			});
		},
		showUnderDevelopmentAlert: function (params) {
			var title = '';
			if (!params.title) {
				params.title = app.name;
			}

			var alertText = `
                        <p class="text-align-center">
                            <i class="f7-icons icon-under-development size-75 text-color-red"></i>
                        </p>
                        <p class="text-align-center">
                            ${LANGUAGE.PROMPT_MSG038}
                        </p>
            `;
			app.dialog.alert(alertText, params.title);
		},

		formatFleetReportData: function (reportData = []) {
			let self = this;
			let newArray = [];
			let assetList = self.methods.getFromStorage('assetList');

			var regexAlarm = RegExp('ALARM_*');
			for (var i = reportData.length - 1; i >= 0; i--) {
				let index = newArray.findIndex(el => el.IMEI === reportData[i].AS_IMEI);
				let detail = {
					DriverName: reportData[i].DRIVER_NAME ? reportData[i].DRIVER_NAME : LANGUAGE.COM_MSG103,
					StartTime: reportData[i].FIRST_ACC_ON,
					StartTimeLocal: reportData[i].FIRST_ACC_ON ? moment(reportData[i].FIRST_ACC_ON, 'YYYY-MM-DD HH:mm:ss.SSS').add(app.data.UTCOFFSET, 'minutes').format('DD/MM/YYYY HH:mm:ss') : '',
					StartLat: reportData[i].BEGIN_LAT,
					StartLng: reportData[i].BEGIN_LNG,
					EndTime: reportData[i].LAST_ACC_OFF,
					EndTimeLocal: reportData[i].LAST_ACC_OFF ? moment(reportData[i].LAST_ACC_OFF, 'YYYY-MM-DD HH:mm:ss.SSS').add(app.data.UTCOFFSET, 'minutes').format('DD/MM/YYYY HH:mm:ss') : '',
					EndLat: reportData[i].END_LAT,
					EndLng: reportData[i].END_LNG,
					InitialOdometer: reportData[i].INITIAL_ODOMETER,
					EndOdometer: parseInt(reportData[i].INITIAL_ODOMETER) + parseInt(reportData[i].TOTAL_MILEAGE),
					TotalMileage: reportData[i].TOTAL_MILEAGE,
					TotalEngineHours: reportData[i].TOTAL_ENGINE_HOURS,
					TotalStationaryTime: reportData[i].TOTAL_STATIC_HOURS,
					TotalMovementTimes: reportData[i].TOTAL_MOVE_TIMES,
					TotalMoveTime: reportData[i].TOTAL_MOVE_HOURS,
					Alarms: {
						GeofenceIn: 0,
						GeofenceOut: 0,
						Overspeed: 0,
						HarshBracking: 0,
						OtherAlarms: 0,
					}
				};

				const keys = Object.keys(reportData[i]);
				var totalAlarmCount = 0;
				for (const key of keys) {
					if (regexAlarm.test(key)) {
						reportData[i][key] = parseInt(reportData[i][key]);
						totalAlarmCount += reportData[i][key];
						switch (key) {
							case 'ALARM_8':
								detail.Alarms.GeofenceIn = reportData[i][key];
								break;
							case 'ALARM_16':
								detail.Alarms.GeofenceOut = reportData[i][key];
								break;
							case 'ALARM_32':
								detail.Alarms.Overspeed = reportData[i][key];
								break;
							case 'ALARM_2097152':
								detail.Alarms.HarshBracking = reportData[i][key];
								break;

							default:
								detail.Alarms.OtherAlarms += reportData[i][key];
						}
					}
				}

				if (index !== -1) {
					newArray[index].Details.push(detail);
					newArray[index].Total.Mileage += parseInt(detail.TotalMileage);
					newArray[index].Total.MoveTimeInHours += parseFloat(moment.duration(detail.TotalMoveTime).asHours().toFixed(3));
					newArray[index].Total.Alarms += totalAlarmCount;
				} else {
					newArray.push({
						Name: reportData[i].AS_NAME,
						IMEI: reportData[i].AS_IMEI,
						ID: assetList[reportData[i].AS_IMEI] && assetList[reportData[i].AS_IMEI].Id ? assetList[reportData[i].AS_IMEI].Id : '',
						Registration: assetList[reportData[i].AS_IMEI] && assetList[reportData[i].AS_IMEI].Registration ? assetList[reportData[i].AS_IMEI].Registration : LANGUAGE.COM_MSG103,
						Make: assetList[reportData[i].AS_IMEI] && assetList[reportData[i].AS_IMEI].Describe1 ? assetList[reportData[i].AS_IMEI].Describe1 : LANGUAGE.COM_MSG103,
						Model: assetList[reportData[i].AS_IMEI] && assetList[reportData[i].AS_IMEI].Describe2 ? assetList[reportData[i].AS_IMEI].Describe2 : LANGUAGE.COM_MSG103,
						Color: assetList[reportData[i].AS_IMEI] && assetList[reportData[i].AS_IMEI].Describe3 ? assetList[reportData[i].AS_IMEI].Describe3 : LANGUAGE.COM_MSG103,
						Year: assetList[reportData[i].AS_IMEI] && assetList[reportData[i].AS_IMEI].Describe4 ? assetList[reportData[i].AS_IMEI].Describe4 : LANGUAGE.COM_MSG103,
						Details: [detail],
						Total: {
							Mileage: parseInt(detail.TotalMileage),
							MoveTimeInHours: parseFloat(moment.duration(detail.TotalMoveTime).asHours().toFixed(3)),
							Alarms: totalAlarmCount
						}
					})
				}
			}

			for (let i = 0; i < newArray.length; i++) {
				if (newArray[i].Total.MoveTimeInHours) {
					newArray[i].Total.MoveTime = moment.duration(newArray[i].Total.MoveTimeInHours, 'hours').format('HH:mm:ss');
				}
			}

			return newArray;
		},
		getStars: function (rating) {
			rating = parseInt(rating);
			var ret = {
				value: 0,
				template: '',
				color: '',
			};
			let ratingVal = rating / 100;
			switch (true) {
				case (ratingVal >= 0.9):
					ret.value = 5;
					ret.color = 'text-color-green';
					break;

				case (ratingVal >= 0.7):
					ret.value = 4;
					ret.color = 'text-color-green';
					break;

				case (ratingVal >= 0.5):
					ret.value = 3;
					ret.color = 'text-color-orange';
					break;

				case (ratingVal >= 0.3):
					ret.value = 2;
					ret.color = 'text-color-red';
					break;

				default:
					ret.value = 1;
					ret.color = 'text-color-red';
			}

			for (var i = 1; i <= 5; i++) {
				if (i <= ret.value) {
					ret.template += `<i class="f7-icons icon-driver-star margin-horizontal-half ${ret.color}"></i>`;
				} else {
					ret.template += '<i class="f7-icons icon-driver-star margin-horizontal-half text-color-gray"></i>';
				}
			}

			return ret;
		},
		getGaugeRaitingDetails: function (raiting) {
			raiting = parseInt(raiting);
			var ret = {
				value: 0,
				borderColor: '#BC2132',
				valueText: 0,
			};

			ret.valueText = raiting;
			ret.value = raiting / 100;
			switch (true) {
				case (ret.value >= 0.75):
					ret.borderColor = '#39B54A';
					break;

				case (ret.value >= 0.5):
					ret.borderColor = '#F7931E';
					break;
			}

			return ret;
		},

	},
	// App routes
	routes: routes,
});

var MapControls = {
	data: {
		Geofences: [],
	},

	isGeofencesShowed: function () {
		return this.data.Geofences.length ? true : false;
	},
	showGeofences: function () {
		var self = this;
		if (!self.isGeofencesShowed()) {
			var geofenceList = app.methods.getFromStorage('geofenceList');
			var groupList = app.methods.getFromStorage('groupList');

			if (!app.methods.isObjEmpty(geofenceList)) {
				const keys = Object.keys(geofenceList);
				for (const key of keys) {
					let geofenceDetails = {
						Name: geofenceList[key].Name,
						Code: geofenceList[key].Code,
					};
					let label = `${LANGUAGE.GEOFENCES_MSG05}: ${geofenceList[key].Name} <br> ${LANGUAGE.COM_MSG104}: `;
					if (geofenceList[key].SelectedAssetList && geofenceList[key].SelectedAssetList.length) {
						label += geofenceList[key].SelectedAssetList.length;
					} else {
						label += '0';
					}
					let markerData = app.methods.getGeofenceDataTable(geofenceList[key], { geogroup: false });
					if (geofenceList[key].GeoType == 1) { //circle
						if (geofenceList[key].Lat && geofenceList[key].Lng && geofenceList[key].Radius) {
							geofenceDetails.polygon = L.circle([geofenceList[key].Lat, geofenceList[key].Lng], {
								...app.data.PolygonCustomization,
								radius: geofenceList[key].Radius,
							}).bindTooltip(label, { permanent: false, direction: 'right' })
								.bindPopup(markerData, { maxWidth: app.data.MaxMapPopupWidth, closeButton: false });
						}
					} else if (geofenceList[key].GeoPolygon) {
						var polygonCoordsArr = geofenceList[key].GeoPolygon.split('((').pop().split('))')[0].split(',');
						var geojsonArr = [];
						for (var i = polygonCoordsArr.length - 1; i >= 0; i--) {
							geojsonArr.push(polygonCoordsArr[i].split(' ').map(parseFloat).reverse());
						}
						geofenceDetails.polygon = L.polygon(geojsonArr, {
							...app.data.PolygonCustomization,
						}).bindTooltip(label, { permanent: false, direction: 'right' })
							.bindPopup(markerData, { maxWidth: app.data.MaxMapPopupWidth, closeButton: false });
					}

					if (geofenceDetails.polygon) {
						geofenceDetails.polygon.addTo(MapTrack);
						self.data.Geofences.push(geofenceDetails);
					}
				}
			}

			if (groupList && groupList.length) {
				for (var i = groupList.length - 1; i >= 0; i--) {
					if (groupList[i].Code != '000000') {
						let geofenceDetails = {
							Name: groupList[i].Name,
							Code: groupList[i].Code,
						};
						let label = `${LANGUAGE.REPORT_PANEL_MSG54}: ${groupList[i].Name} <br> ${LANGUAGE.COM_MSG104}: `;
						if (groupList[i].Assets && groupList[i].Assets.length) {
							label += groupList[i].Assets.length;
						} else {
							label += '0';
						}
						let markerData = app.methods.getGeofenceDataTable(groupList[i], { geogroup: true });
						if (groupList[i].GeoType == 1) { //circle
							if (groupList[i].Lat && groupList[i].Lng && groupList[i].Radius) {
								geofenceDetails.polygon = L.circle([groupList[i].Lat, groupList[i].Lng], {
									...app.data.PolygonCustomization,
									radius: groupList[i].Radius,
								}).bindTooltip(label, { permanent: false, direction: 'right' })
									.bindPopup(markerData, { maxWidth: app.data.MaxMapPopupWidth, closeButton: false });
							}
						} else if (groupList[i].GeoPolygon) {
							var polygonCoordsArr = groupList[i].GeoPolygon.split('((').pop().split('))')[0].split(',');
							var geojsonArr = [];
							for (var y = polygonCoordsArr.length - 1; y >= 0; y--) {
								geojsonArr.push(polygonCoordsArr[y].split(' ').map(parseFloat).reverse());
							}
							geofenceDetails.polygon = L.polygon(geojsonArr, {
								...app.data.PolygonCustomization,
							}).bindTooltip(label, { permanent: false, direction: 'right' })
								.bindPopup(markerData, { maxWidth: app.data.MaxMapPopupWidth, closeButton: false });

						}
						if (geofenceDetails.polygon) {
							geofenceDetails.polygon.addTo(MapTrack);
							self.data.Geofences.push(geofenceDetails);
						}
					}
				}
			}
		}
	},
	hideGeofences: function () {
		var self = this;
		if (self.data.Geofences && self.data.Geofences.length) {
			for (var i = self.data.Geofences.length - 1; i >= 0; i--) {
				if (self.data.Geofences[i].polygon) {
					MapTrack.removeLayer(self.data.Geofences[i].polygon);
				}
			}
			self.data.Geofences.length = 0;
		}
	},
	removeGeofence: function (code) {
		var self = this;
		if (code && self.data.Geofences && self.data.Geofences.length) {
			let index = self.data.Geofences.findIndex(el => el.Code == code);
			if (index != -1) {
				MapTrack.removeLayer(self.data.Geofences[index].polygon);
			}
		}
	}
};

var snapshotsView,dashboardView, cctvView , newtemplateView, createtaskView, createorderView;

var leftView = app.views.create('.view-left', {
	//url: app.view.pushStateRoot ? app.view.pushStateRoot : '/',
	url: '/panel-left/',
	name: 'view-left',
	//allowDuplicateUrls: true,
	//reloadPages: true,
	xhrCache: false,
	/*xhrCacheIgnore: [
		  './resources/pages/asset-playback-show.html',
		  './resources/pages/asset-playback.html'
	  ],*/
	on: {
		init: function () {

		},

		/*routeChanged: function(newRoute, previousRoute, router){
	
			}*/
	}

});

var reportView = app.views.create('.view-report', {
	//url: app.view.pushStateRoot ? app.view.pushStateRoot : '/',
	url: '/report-show/',
	name: 'report-show',
	reloadPages: true,
	allowDuplicateUrls: true,

});
var additionalInfoView = app.views.create('.view-additional-info', {
	url: '/empty/',
	name: 'additional-info',
	reloadPages: true,
	allowDuplicateUrls: true,
});
var adsInfoView = app.views.create('.view-ads-info', {
	url: '/empty/',
	name: 'ads-info',
	reloadPages: true,
	allowDuplicateUrls: true,
});
/*var cctvView = app.views.create('.view-cctv', {
	url: '/cctv/',
	name: 'cctv',
	reloadPages: true,
	allowDuplicateUrls: true,
});*/

/*var dashboardView = app.views.create('.view-dashboard', {
	//url: app.view.pushStateRoot ? app.view.pushStateRoot : '/',
	url: '/dashboard/',
	name: 'dashboard'
});*/

// Init/Create main view
var mainView = app.views.create('.view-main', {
	//url: app.view.pushStateRoot ? app.view.pushStateRoot : '/',
	url: '/',
	name: 'view-main'
});

var reportShowPopup = app.popup.create({
	el: '.popup-fullscreen-report',
	backdrop: false,
});

var dashboardPopup = app.popup.create({
	el: '.popup-fullscreen-dashboard',
	backdrop: false,
});

var snapShotsPopup = app.popup.create({
	el: '.popup-fullscreen-snapshots',
	backdrop: false,
});
var photoEventsPopup = app.popup.create({
	el: '.popup-fullscreen-photoevents',
	backdrop: false,
});
var videoEventsPopup = app.popup.create({
	el: '.popup-fullscreen-videoevents',
	backdrop: false,
});
var videoLoopsPopup = app.popup.create({
	el: '.popup-fullscreen-videoloops',
	backdrop: false,
});


var additionalInfoPopup = app.popup.create({
	el: '.popup-additional-info',
	//backdrop: false,
});
var cctvPopup = app.popup.create({
	el: '.popup-fullscreen-cctv',
	backdrop: false,
});
var newtemplatePopup = app.popup.create({
    el: '.popup-fullscreen-newtemplate',
    backdrop: false,

});
 
var createtaskPopup = app.popup.create({
    el: '.popup-fullscreen-createtask',
    backdrop: false,
});

var createorderPopup = app.popup.create({
    el: '.popup-fullscreen-createorder',
    backdrop: false,
});


$$('body').on('change keyup input click', '.only_numbers', function () {
	if (this.value.match(/[^0-9-]/g)) {
		this.value = this.value.replace(/[^0-9-]/g, '');
	}
});

$$('body').on('submit', '.login-form', function (e) {
	e.preventDefault();
	//preLogin();
	app.methods.hideKeyboard();
	app.methods.login(this);
	return false;
});
$$('body').on('click', '.demo-login', function (e) {

	app.methods.hideKeyboard();
	switch (parsedDealer) {
		case 'cbhgroup':
			$$("input[name='username']").val('CBH Demo');
			$$("input[name='password']").val('888888');
			break;
		case 'isstrack':
			$$("input[name='username']").val('issdemo');
			$$("input[name='password']").val('888888');
			break;
		case 'fridgewatch':
			$$("input[name='username']").val('fridgewatchdemo');
			$$("input[name='password']").val('888888');
			break;
		default:
			$$("input[name='username']").val('demochile');
			$$("input[name='password']").val('999999');
	}
	app.methods.login();

});

$$('body').on('click', '.password-toggle', function () {
	var password = $(this).siblings("input");
	if (password.prop("type") == "text") {
		password.prop("type", "password");
	} else {
		password.prop("type", "text");
	}
	$$(this).toggleClass('text-color-gray');
});

$$('body').on('click', '.smart-select-page .item-divider', function () {
	var $el = $$(this);
	var elArr = $(this).nextUntil('li.item-divider');
	var state = !$el.data('state');

	if (elArr && elArr.length) {
		for (var i = elArr.length - 1; i >= 0; i--) {
			$$(elArr[i]).find('input[type="checkbox"]').prop("checked", state).change(); //[0].checked = state; //.dispatchEvent(new Event('change', { 'bubbles': true }))
		}
	}
	$el.data('state', state);
});
//var dashboardPopup = app.popup.get('.popup-fullscreen-dashboard');

$$('body').on('change', '.leaflet-control-layers-selector', function () {
	let customOverlay = $$(this).parent().find('.customOverlay');
	if (!customOverlay.length) {
		return;
	}

	let type = customOverlay.data('type');
	let mapSettingsObg = app.methods.getFromStorage('mapSettings');
	if (customOverlay.hasClass('mapSwitcherWrapper')) {
		mapSettingsObg['map'] = type;
	} else {
		mapSettingsObg[type] = this.checked;
	}

	app.methods.setInStorage({ name: 'mapSettings', data: mapSettingsObg });
});



$$('.popup-fullscreen-snapshots').on('popup:open', function (popup) {
	if (!snapshotsView) {
		snapshotsView = app.views.create('.view-snapshots', {
			url: '/gallery-snapshots/',
			name: 'gallery-snapshots',
			xhrCache: false,
			reloadPages: true,
			allowDuplicateUrls: true,
		});
	}
});
$$('.popup-fullscreen-snapshots').on('popup:closed', function (popup) {
	if (snapshotsView) {
		snapshotsView.destroy();
		snapshotsView = false;
		$$('.view-snapshots').empty();
	}
});

$$('.popup-fullscreen-photoevents').on('popup:open', function (popup) {
	if (!snapshotsView) {
		snapshotsView = app.views.create('.view-photoevents', {
			url: '/gallery-photoevents/',
			name: 'gallery-photoevents',
			xhrCache: false,
			reloadPages: true,
			allowDuplicateUrls: true,
		});
	}
});
$$('.popup-fullscreen-photoevents').on('popup:closed', function (popup) {
	if (snapshotsView) {
		snapshotsView.destroy();
		snapshotsView = false;
		$$('.view-photoevents').empty();
	}
});


$$('.popup-fullscreen-videoevents').on('popup:open', function (popup) {
	if (!snapshotsView) {
		snapshotsView = app.views.create('.view-videoevents', {
			url: '/gallery-videoevents/',
			name: 'gallery-videoevents',
			xhrCache: false,
			reloadPages: true,
			allowDuplicateUrls: true,
		});
	}
});
$$('.popup-fullscreen-videoevents').on('popup:closed', function (popup) {
	if (snapshotsView) {
		snapshotsView.destroy();
		snapshotsView = false;
		$$('.view-videoevents').empty();
	}
});


$$('.popup-fullscreen-videoloops').on('popup:open', function (popup) {
	if (!snapshotsView) {
		snapshotsView = app.views.create('.view-videoloops', {
			url: '/gallery-videoloops/',
			name: 'gallery-videoloops',
			xhrCache: false,
			reloadPages: true,
			allowDuplicateUrls: true,
		});
	}
});
$$('.popup-fullscreen-videoloops').on('popup:closed', function (popup) {
	if (snapshotsView) {
		snapshotsView.destroy();
		snapshotsView = false;
		$$('.view-videoloops').empty();
	}
});


$$('.popup-fullscreen-dashboard').on('popup:open', function (popup) {
	if (!dashboardView) {
		dashboardView = app.views.create('.view-dashboard', {
			url: '/dashboard/',
			name: 'dashboard',
			xhrCache: false,
			reloadPages: true,
			allowDuplicateUrls: true,
		});
	}
});
$$('.popup-fullscreen-dashboard').on('popup:closed', function (popup) {
	if (dashboardView) {
		dashboardView.destroy();
		dashboardView = false;
		$$('.view-dashboard').empty();
	}
	if (AutoUpdateDashboardDataTimer) {
		clearInterval(AutoUpdateDashboardDataTimer);
	}
});
$$('.popup-fullscreen-cctv').on('popup:open', function (popup) {
	if (!cctvView) {
		cctvView = app.views.create('.view-cctv', {
			url: '/cctv/',
			name: 'cctv',
			xhrCache: false,
			reloadPages: true,
			allowDuplicateUrls: true,
		});
	}
});
$$('.popup-fullscreen-cctv').on('popup:closed', function (popup) {
	if (cctvView) {
		cctvView.destroy();
		cctvView = false;
		$$('.view-cctv').empty();
	}
});



newtemplateView = app.views.create('.view-newtemplate', {
	url: '/job-despatch/new-template/',
	name: 'new-template',
	reloadPages: true,
	allowDuplicateUrls: true,
});
createtaskView = app.views.create('.view-createtask', {
	url: '/job-despatch/create/',
	name: 'create-task',
	reloadPages: true,
	allowDuplicateUrls: true,
});
createorderView = app.views.create('.view-createorder', {
	url: '/job-despatch/new-order/',
	name: 'create-order',
	reloadPages: true,
	allowDuplicateUrls: true,
});

$$('.popup-fullscreen-newtemplate').on('popup:open', function(popup) {
});
$$('.popup-fullscreen-newtemplate').on('popup:closed', function(popup) {
		// if (newtemplateView) {
		//     newtemplateView.destroy();
		//      newtemplateView = false;
		//     $$('.view-newtemplate').empty();
		// }
 
			newtemplateView.router.clearPreviousHistory();	 
});
$$('.popup-fullscreen-createtask').on('popup:open', function(popup) {
});
$$('.popup-fullscreen-createtask').on('popup:closed', function(popup) {
		createtaskView.router.clearPreviousHistory();
		leftView.router.refreshPage();
});
$$('.popup-fullscreen-createorder').on('popup:open', function(popup) {
});
$$('.popup-fullscreen-createorder').on('popup:closed', function(popup) {
		createorderView.router.clearPreviousHistory();
});




$$('.popup-fullscreen-report').on('popup:opened', function (popup) {
	/*console.log('Popup opened');*/
});

$$('.popup-fullscreen-report').on('popup:close', function (popup) {
	reportView.router.clearPreviousHistory();
	if (DATATABLEReport) {
		DATATABLEReport.destroy();
	}
});

// Function to convert an img URL to data URL
/*function getBase64FromImageUrl(url, callback) {
	var img = new Image();
		img.crossOrigin = "anonymous";
	img.onload = function () {
		var canvas = document.createElement("canvas");
		canvas.width =this.width;
		canvas.height =this.height;
		var ctx = canvas.getContext("2d");
		ctx.drawImage(this, 0, 0);
		var dataURL = canvas.toDataURL("image/png");

		//return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

		dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
		callback(dataURL);
	};
	img.src = url;
}*/

function openLiveStream(imei, title, ch) {
	if (!window.popupLiveVideoForm) {
		window.popupLiveVideoForm = {};
		window.popupLiveVideoNumbers = 0;
	}

	imei = "0" + parseInt(imei);
	let id = "player" + imei + "CH" + ch;

	if (window.popupLiveVideoForm[id]) {
		window.popupLiveVideoForm[id].show();
	}
	else {
		window.popupLiveVideoNumbers += 1;
		let videoPopupWidth = 305;
		let autoClose = 10;
		let cctvSrcParams = {
			lang: "en",
			devIdno: imei,
			//jsessionKey: '48D39CE6F74C4262E47AA1464DBFDC07',
			index: ch,
			//channel: 1,
			close: autoClose
		}
		let src = API_URL.CCTV_SRC2 + "?" + app.utils.serializeObject(cctvSrcParams);

		let div = document.createElement("div");
		div.innerHTML = `<div id='${id}' class='player-modal' style='z-index: 10000; left: ${videoPopupWidth * popupLiveVideoNumbers}px;'>
      <div class='title' >${title} - CH ${ch}</div>
      <a href="javascript:closeLiveStream('${id}')">
        <div class='close'>&#10006;</div>
      </a>
      <iframe src='${src}' id='livestream' height='100%' width='100%' title='Live' allow='fullscreen'></iframe>
      </div>`;
		document.body.appendChild(div);

		let $videoPopup = $('#' + id);
		$videoPopup.show();
		$videoPopup.draggable();
		window.popupLiveVideoForm[id] = $videoPopup;
	}
}
function closeLiveStream(id) {
	$(`#${id}`).hide()
}