<!--suppress JSAnnotator -->
<template>
<!-- Page, data-name contains page name which can be used in callbacks -->
		<div class="page " data-name="asset-alarm"> <!-- page-with-subnavbar -->
		<!-- Top Navbar -->
			<div class="navbar">
				<div class="navbar-inner">
					<div class="left">
						<a href="#" class="link back">
							<i class="icon icon-back"></i>
						</a>
					</div>
					<div class="title sliding">{{@global.LANGUAGE.ASSET_LIST_MSG03}}</div>
					<div class="right">
						<!-- <a href="#" class="link">
												 <i class="f7-icons icon-notification"></i>
											 </a>    -->
					</div>

				</div>
			</div>

			<div class="bottom-section-wrapper bottom-section-button-wrapper bg-color-white">
				<div class="row">
					<label for="submit-form" class="col button button-fill color-green elevation-2" tabindex="0" >{{@global.LANGUAGE.COM_MSG06}}</label>
				</div>
			</div>

			<!-- Scrollable page content-->
			<form name="AssetAlarmForm" class="page-content">
				<input type="hidden" name="IMEI" value="{{IMEI}}">
				<input type="submit" id="submit-form" class="display-none" />
				<div class="block-title text-color-darkgray">{{@global.LANGUAGE.ASSET_LIST_MSG03}}</div>
				<div class="block">
					<p>{{@global.LANGUAGE.PROMPT_MSG000}}</p>
				</div>

				{{#if ShowAdditionalBlocks}}
					<div key="IgnoreBetween" class="list no-hairline-bottom">
						<ul>
							<li class="item-content">
								<div class="item-inner">
									<div class="item-title">{{@global.LANGUAGE.COM_MSG71}}</div>
									<div class="item-after">
										<label class="toggle toggle-ignore-between">
											<input type="checkbox" name="IgnoreBetweenState" {{#if IgnoreBetweenState}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
										</label>
									</div>
								</div>
							</li>
							<li>
								<div class="item-content item-input {{#unless IgnoreBetweenState}} disabled {{/unless}}">
									<div class="item-media text-color-lightgray">
										<i class="f7-icons icon-time-period"></i>
									</div>
									<div class="item-inner">
										<div class="row">
											<div class="col">
												<div class="item-title item-label ">{{@global.LANGUAGE.COM_MSG69}}</div>
												<div class="item-input-wrap">
													<input type="text" name="PickerStart" readonly="readonly" />
												</div>
											</div>
											<div class="col">
												<div class="item-title item-label ">{{@global.LANGUAGE.COM_MSG70}}</div>
												<div class="item-input-wrap">
													<input type="text" name="PickerEnd" readonly="readonly" />
												</div>
											</div>
										</div>
									</div>
								</div>
							</li>
							<li>
								<a class="item-link smart-select custom-smart-select smart-select-days-of-week {{#unless IgnoreBetweenState}} disabled {{/unless}}" data-open-in="popover">
									<select name="IgnoreDays" multiple>
										{{#each DaysOfWeek}}
											<option value="{{val}}" data-display-as="{{displayAs}}" {{#if selected}} selected {{/if}}>{{name}}</option>
										{{/each}}
									</select>
									<div class="item-content item-input">
										<div class="item-media text-color-lightgray">
											<i class="f7-icons icon-calendar"></i>
										</div>
										<div class="item-inner">
											<div class="item-title item-label">{{@global.LANGUAGE.COM_MSG72}}</div>
										</div>
									</div>
								</a>
							</li>
						</ul>
					</div>
				{{/if}}

				{{#if ShowAlarmList}}
					<div key="AlarmList" class="list no-hairline-bottom">
						<ul>
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title">Turn On email notifications</div>
									<div class="item-after">
								  		<label class="toggle toggle-all-alarm-email">
											<input type="checkbox" name="checkbox-alarm-all-email" {{#if toggleEmailEl}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title">Turn On push notifications</div>
									<div class="item-after">
								  		<label class="toggle toggle-all-alarm-push">
											<input type="checkbox" name="checkbox-alarm-all-push" {{#if togglePushEl}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>
							
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title">{{TurnOnAll.title}}</div>
									<div class="item-after">
								  		<label class="toggle toggle-all-alarm">
											<input type="checkbox" name="checkbox-alarm-all" {{#if TurnOnAll.state}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>

							{{#each Alarms}}
								<li>
									<label class="item-checkbox item-content">
										<input type="checkbox" name="checkbox-alarm" value="{{this.val}}" {{#if this.state}}checked="checked"{{/if}}/>
										<i class="icon icon-checkbox"></i>
										<div class="item-inner">
											<div class="item-title">{{this.title}}</div>
										</div>
									</label>
								</li>
							{{/each}}
						</ul>
					</div>

					{{#if ShowAdditionalBlocks}}

					<div key="Offline" class="list no-hairline-bottom ">
						<ul>
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG32}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG0100}}"></i></div>
									<div class="item-after">
								  		<label class="toggle">
											<input type="checkbox" name="checkbox-alarm" class="disablingController" value="67108864" {{#if OfflineState}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>
							{{#OfflineOptions}}
								<li>
									<label class="item-checkbox item-content {{#unless ../OfflineState}}disabled{{/unless}}">
										<input type="checkbox" name="offline-option" value="{{Value}}" {{#if State}}checked="checked"{{/if}}/>
										<i class="icon icon-checkbox"></i>
										<div class="item-inner">
											<div class="item-title">{{Name}}</div>
										</div>
									</label>
								</li>
							{{/OfflineOptions}}
						</ul>
					</div>

					<div key="Overspeed" class="list no-hairline-bottom">
						<ul>
							<li class="item-content">
							  	<div class="item-inner">
									<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG23}}</div>
									<div class="item-after">
								  		<label class="toggle">
											<input type="checkbox" name="checkbox-alarm" class="disablingController" value="32" {{#if OverspeedState}}checked="checked"{{/if}}>
											<span class="toggle-icon"></span>
								  		</label>
									</div>
							  	</div>
							</li>
							<li>
							    <label class="item-radio item-content disablingObj {{#unless OverspeedState}}disabled{{/unless}}">
							        <input type="radio" name="overspeed-type" value="1" {{#js_if ' !this.SpeedingMode || this.SpeedingMode == 1 '}} checked{{/js_if}}/>
							        <i class="icon icon-radio"></i>
							        <div class="item-inner">
							          	<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG31}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG098}}"></i></div>
							        </div>
							    </label>
							</li>

							<li>
							    <label class="item-radio item-content disablingObj {{#unless OverspeedState}}disabled{{/unless}}">
							        <input type="radio" name="overspeed-type" value="2" {{#js_if ' this.SpeedingMode == 2 '}} checked{{/js_if}} />
							        <i class="icon icon-radio"></i>
							        <div class="item-inner">
							          	<div class="item-title">{{@global.LANGUAGE.ASSET_ALARM_MSG30}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG099}}"></i></div>
							        </div>
							    </label>
							</li>
						</ul>
					</div>


					{{/if}}
				{{else}}
					<div key="AlarmListPreloader" class="block block-strong text-align-center">
						<div class="preloader color-red"></div>
					</div>
				{{/if}}

			</form>
		</div>
</template>


<script>
  // script must return component object
	return {
		data: function () {
			let self = this;

			let assetList = self.$app.methods.getFromStorage('assetList');
			let IMEI = decodeURIComponent(self.$route.params.imei);
			let index = IMEI.indexOf(',');
console.log('asscur',assetList[IMEI])
			let maxSpeedUnit = index === -1 ? assetList[IMEI].Unit : assetList[IMEI.split(',')[0]].Unit;
			let maxSpeed = index === -1 ? assetList[IMEI].MaxSpeed : 80; //index === -1 ? Protocol.Helper.getSpeedValue(maxSpeedUnit, asset.MaxSpeed);

			let ret = {
				AlarmListType: 3,
				ShowAlarmList: false,
				Alarms: [],
				ToggleAllAlarms: false,
				TurnOnAll: {
					state: false,
					title: LANGUAGE.ASSET_ALARM_MSG26,
				},
				toggleEmailEl: false,
				togglePushEl: false,
				IMEI: IMEI,
				MaxSpeedUnit: maxSpeedUnit,
				MaxSpeed: Protocol.Helper.getSpeedValue(maxSpeedUnit, maxSpeed),

				ShowAdditionalBlocks: false,
				IgnoreBetweenState: false,
				TimePickerStart: false,
				TimePickerEnd: false,
				DaysOfWeek: [],
				DaysOfWeekSelect: false,
			};
 			//console.log(ret);
			return ret;
		},
		methods: {
			getAlarmOptions: function(){
				let self = this;

				if (!self.$route.params || !self.$route.params.imei ) {
					console.log('There is no params or imei param');
				}else{

					let imeiArr = self.IMEI.split(',');
					let assetList = self.$app.methods.getFromStorage('assetList');

					if (imeiArr.length > 1) {
						let AlarmListType = 3;
						/*switch (self.$route.query.solution){
							case 'track':
							case 'watch':
							case 'boat_watch':
							case 'wititrack':
								AlarmListType = 2;
								break;

							case 'protect':
							case 'qprotect':
							case 'witiprotect':
							case 'witiqprotect':
								AlarmListType = 1;
								break;
						}*/
						if ( self.$route.query.solution.SolutionType && self.$route.query.solution.SolutionType.toLowerCase().indexOf('track') !== -1 ||
							self.$route.query.solution.SolutionType && self.$route.query.solution.SolutionType.toLowerCase().indexOf('watch') !== -1
						){
							AlarmListType = 2;
						}else if(self.$route.query.solution.SolutionType && self.$route.query.solution.SolutionType.toLowerCase().indexOf('protect') !== -1){
							AlarmListType = 1;
						}

						self.loadAlarmList({
							AlarmListType: AlarmListType,
							AssetType: assetList[imeiArr[0]] ? assetList[imeiArr[0]].AssetType : '',
							SolutionType : assetList[imeiArr[0]] ? assetList[imeiArr[0]].SolutionType : '',
							AlarmOptions: 0,
						});
					}else{

						let asset = assetList[self.$route.params.imei];

						if (asset) {
							if (asset.SolutionType && asset.SolutionType.toLowerCase() === 'track' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'watch' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'boat_watch' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'wititrack' ||
								asset.SolutionType && asset.SolutionType.toLowerCase() === 'witiqprotect' ||
								asset.SolutionType && asset.SolutionType.toLowerCase().indexOf('track') !== -1 ||
								asset.SolutionType && asset.SolutionType.toLowerCase().indexOf('watch') !== -1)
							{ console.log('11');
								let userInfo = self.$app.methods.getFromStorage('userInfo');
								let data = {
									MajorToken: userInfo.MajorToken,
									MinorToken: userInfo.MinorToken,
									IMEI: self.$route.params.imei
								};
								app.request.post(API_URL.GET_ALERT_CONFIG, data, function (result, xhr, status) {
									if (result && typeof result != 'object') {
										result = JSON.parse(result);
									}
									if (result && result.MajorCode == '000') {
										self.loadAlarmList({
											AlarmListType: 2, //live
											AssetType: asset.AssetType,
											SolutionType: asset.SolutionType,
											AlarmOptions: result.Data.AlertTypes,
											LiveAssetSettings: result.Data,
										});
									} else {
										self.loadAlarmList({
											AlarmListType: 2,    //live
											AssetType: asset.AssetType,
											SolutionType: asset.SolutionType,
											AlarmOptions: asset.AlarmOptions,
										});
									}
									 self.$setState({
											toggleEmailEl:  result?.Data?.IsEmailNotification,
											togglePushEl:  result?.Data?.IsPushNotification,
									 })
									console.log(self.loadAlarmList);
								});

							}else if(asset.SolutionType && asset.SolutionType.toLowerCase() === 'loc8' ||
								asset.SolutionType && asset.SolutionType.toLowerCase().indexOf('loc8') !== -1
							){ console.log('112');
								self.loadAlarmList({
									AlarmListType: 3,
									AssetType: asset.AssetType,
									SolutionType: asset.SolutionType,
									AlarmOptions: asset.AlarmOptions,

								});
							}else{ console.log('113');
								self.loadAlarmList({
									AlarmListType: 1,     //protect
									AssetType: asset.AssetType,
									SolutionType: asset.SolutionType,
									AlarmOptions: asset.AlarmOptions,
								});
							}
						}
					}
				}

			},
			loadAlarmList: function(data){
				let self = this;

				if (data && data.AlarmListType) {
					let alarmList = self.getAlarmListByType(data.AlarmListType, data.AssetType, data.SolutionType);
console.log(alarmList)
					for (var i = alarmList.length - 1; i >= 0; i--) {
						if (data.AlarmOptions & alarmList[i].val) {
							alarmList[i].state = false;
						}
					}

					self.$setState({
						AlarmListType: data.AlarmListType,
						ShowAlarmList: true,
						Alarms: alarmList,
						IgnoreBetweenState: !!(data && data.LiveAssetSettings && data.LiveAssetSettings.IsIgnore == 1),
						SpeedingMode: data && data.LiveAssetSettings && data.LiveAssetSettings.SpeedingMode ? data.LiveAssetSettings.SpeedingMode : 1
					});

					if (data.AlarmListType == 2) {
						var offlineOptions = {};
						if (data && data.LiveAssetSettings && data.LiveAssetSettings.OfflineHours) {
							offlineOptions = Protocol.Helper.getOfflineAlarmOptions(data.LiveAssetSettings.OfflineHours);
						}else{
							offlineOptions = Protocol.Helper.getOfflineAlarmOptions();
						}

						self.$setState({
							ShowAdditionalBlocks: !data.AssetType || data.AssetType && data.AssetType.toLowerCase() !== 'boat' && data.AssetType.toLowerCase() !== 'jetski',
							OverspeedState: !(data.AlarmOptions & 32),
							OfflineState: !(data.AlarmOptions & 67108864),
						});
						self.$app.utils.nextFrame(() => {
							self.$setState({
								OfflineOptions: offlineOptions,
							});
						})

						self.initIgnoreBetweenBlock(data.LiveAssetSettings);
					}
					self.initToggleAllAlarms(data.AlarmOptions);

				}
			},
			initIgnoreBetweenBlock: function(params = {}){
				let self = this;

				if (params.BeginTime) {
					params.BeginTime = moment(params.BeginTime,'HH:mm').add(app.data.UTCOFFSET,'minutes').format('HH:mm');
				}
				if (params.EndTime) {
					params.EndTime = moment(params.EndTime,'HH:mm').add(app.data.UTCOFFSET,'minutes').format('HH:mm');
				}

				let StartTimeValArray = params.BeginTime ? params.BeginTime.split(':') : [];
				let EndTimeInputArray = params.EndTime ? params.EndTime.split(':') : [];
				let ignoreBetweenStateEl = self.$el.find('[name="IgnoreBetweenState"]');
				let daysOfWeekEl = self.$el.find('.smart-select-days-of-week');
				let daysOfWeekArray = [
					{
						val: 0,
						name: LANGUAGE.COM_MSG38,
						displayAs: LANGUAGE.COM_MSG45,
						selected: false,
					},
					{
						val: 1,
						name: LANGUAGE.COM_MSG39,
						displayAs: LANGUAGE.COM_MSG46,
						selected: false,
					},
					{
						val: 2,
						name: LANGUAGE.COM_MSG40,
						displayAs: LANGUAGE.COM_MSG47,
						selected: false,
					},
					{
						val: 3,
						name: LANGUAGE.COM_MSG41,
						displayAs: LANGUAGE.COM_MSG48,
						selected: false,
					},
					{
						val: 4,
						name: LANGUAGE.COM_MSG42,
						displayAs: LANGUAGE.COM_MSG49,
						selected: false,
					},
					{
						val: 5,
						name: LANGUAGE.COM_MSG43,
						displayAs: LANGUAGE.COM_MSG50,
						selected: false,
					},
					{
						val: 6,
						name: LANGUAGE.COM_MSG44,
						displayAs: LANGUAGE.COM_MSG51,
						selected: false,
					},
				];

				if (!StartTimeValArray || !StartTimeValArray.length) {
					StartTimeValArray = ['07', '00'];
				}
				if (!EndTimeInputArray || !EndTimeInputArray.length) {
					EndTimeInputArray = ['18', '00'];
				}

				ignoreBetweenStateEl.on('change', function(){
					self.$setState({
						IgnoreBetweenState: this.checked
					});
				});

				self.TimePickerStart = app.picker.create({
					inputEl: self.$el.find('[name="PickerStart"]'),
					rotateEffect: true,
					value: StartTimeValArray,
					cols: [
						{
							textAlign: 'center',
							values: (function() {
								var arr = [];
								for (var i = 0; i <= 23; i++) { arr.push(i < 10 ? '0' + i : i); }
								return arr;
							})(),
						},
						// Divider
						{
							divider: true,
							content: ':'
						},
						// Minutes
						{
							textAlign: 'center',
							values: (function() {
								var arr = [];
								for (var i = 0; i <= 59; i++) { arr.push(i < 10 ? '0' + i : i); }
								return arr;
							})(),
						}
					],
					renderToolbar: function () {
						return '';
					},
					formatValue: function(values, displayValues) {
						return values[0] + ':' + values[1];
					},
				});

				self.TimePickerEnd = app.picker.create({
					inputEl: self.$el.find('[name="PickerEnd"]'),
					rotateEffect: true,
					value: EndTimeInputArray,
					cols: [
						{
							textAlign: 'center',
							values: (function() {
								var arr = [];
								for (var i = 0; i <= 23; i++) { arr.push(i < 10 ? '0' + i : i); }
								return arr;
							})(),
						},
						// Divider
						{
							divider: true,
							content: ':'
						},
						// Minutes
						{
							textAlign: 'center',
							values: (function() {
								var arr = [];
								for (var i = 0; i <= 59; i++) { arr.push(i < 10 ? '0' + i : i); }
								return arr;
							})(),
						}
					],
					renderToolbar: function () {
						return '';
					},
					formatValue: function(values, displayValues) {
						return values[0] + ':' + values[1];
					},
				});

				if (params.Weeks) {
					let selectedDays = params.Weeks.split(',');
					if (selectedDays && selectedDays.length) {
						for (let i = selectedDays.length - 1; i >= 0; i--) {
							let dayIndex = daysOfWeekArray.findIndex(x => x.val === parseInt(selectedDays[i],10));
							if (dayIndex != -1) {
								daysOfWeekArray[dayIndex].selected = true;
							}
						}
					}
				}

				self.$setState({
					DaysOfWeek: daysOfWeekArray,

				});

				self.DaysOfWeekSelect = app.smartSelect.create({
					el: daysOfWeekEl,
					openIn: 'popover',
				});


			},
			initToggleAllAlarms: function(alarmOptions = 0){
				let self = this;
				let checkboxes = self.$el.find('[name = "checkbox-alarm"]');

				self.ToggleAllAlarms = app.toggle.create({
					el: self.$el.find('.toggle-all-alarm'),
					on: {
						change: function () {
							for (var i = checkboxes.length - 1; i >= 0; i--) {
								checkboxes[i].checked = this.checked;
								if (checkboxes[i].value == '32' || checkboxes[i].value == '67108864') {
									$$(checkboxes[i]).change();
								}
							}

						}
					}
				});
				alarmOptions = parseInt(alarmOptions,10);
				if (alarmOptions === 0) {
					if (!self.ToggleAllAlarms.checked) {
						self.ToggleAllAlarms.toggle();
					}
				}
				
				let toggleEmailEl = self.$el.find('[name="checkbox-alarm-all-email"]');
				toggleEmailEl.on('change', function () {
				//console.log('111')
				  self.$setState({
					toggleEmailEl: this.checked
				  });
				});
				let togglePushEl = self.$el.find('[name="checkbox-alarm-all-push"]');
				togglePushEl.on('change', function () {
				//console.log('222')
				  self.$setState({
					togglePushEl: this.checked
				  });
				});
				
			},
			getAlarmListByType: function(type, assetType, solutionType){
				//console.log(type, assetType, solutionType)
				let self = this;
				let ret = [];
				let userAlarmSettings = self.$app.methods.getFromStorage('userAlarmSettings');
				if (type) {
					type = parseInt(type, 10);
					assetType ? assetType = assetType.toLowerCase() : '';
					solutionType ? solutionType = solutionType.toLowerCase() : '';
					switch (type){
						case 2:     //live
							if(assetType === 'boat' || assetType === 'jetski'){
								ret = [
									{
										state: true,
										val: 131072,
										title: userAlarmSettings && userAlarmSettings.Input1High ? userAlarmSettings.Input1High : LANGUAGE.ASSET_ALARM_MSG02, //customAlarm
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
									{
										state: true,
										val: 65536,
										title: LANGUAGE.ASSET_ALARM_MSG10, //accOff
									},
									{
										state: true,
										val: 32768,
										title: LANGUAGE.ASSET_ALARM_MSG11, //accOn
									},
									{
										state: true,
										val: 1048576,
										title: LANGUAGE.ASSET_ALARM_MSG03, //Shore Power Disconnect
									},
									{
										state: true,
										val: 524288,
										title: LANGUAGE.ASSET_ALARM_MSG37, //Outboard Engine Removal
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 8,
										title: LANGUAGE.ASSET_ALARM_MSG12, //geofenceIn
									},
									{
										state: true,
										val: 16,
										title: LANGUAGE.ASSET_ALARM_MSG13, //geofenceOut
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG09, //power
									},
								]
							}else if(solutionType && solutionType.toLowerCase() === 'wititrack'){
								ret = [
									{
										state: true,
										val: 131072,
										title: LANGUAGE.ASSET_ALARM_MSG39, //customAlarm, negative input,  witi alarm
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 8,
										title: LANGUAGE.ASSET_ALARM_MSG12, //geofenceIn
									},
									{
										state: true,
										val: 16,
										title: LANGUAGE.ASSET_ALARM_MSG13, //geofenceOut
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG18, //mainBatteryFail
									},
								]
							}else{
								ret = [
									{
										state: true,
										val: 65536,
										title: LANGUAGE.ASSET_ALARM_MSG10, //accOff
									},
									{
										state: true,
										val: 32768,
										title: LANGUAGE.ASSET_ALARM_MSG11, //accOn
									},
									{
										state: true,
										val: 1048576,
										title: LANGUAGE.ASSET_ALARM_MSG20, //custom2LowAlarm
									},
									{
										state: true,
										val: 131072,
										title: userAlarmSettings && userAlarmSettings.Input1High ? userAlarmSettings.Input1High : LANGUAGE.ASSET_ALARM_MSG22, //customAlarm
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 8,
										title: LANGUAGE.ASSET_ALARM_MSG12, //geofenceIn
									},
									{
										state: true,
										val: 16,
										title: LANGUAGE.ASSET_ALARM_MSG13, //geofenceOut
									},
									{
										state: true,
										val: 128,
										title: LANGUAGE.ASSET_ALARM_MSG27, //illegalIgnition
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG18, //mainBatteryFail
									},
									{
										state: true,
										val: 2,
										title: LANGUAGE.ASSET_ALARM_MSG19, //sosAlarm
									},
									{
										state: true,
										val: 256,
										title: LANGUAGE.ASSET_ALARM_MSG07, //tilt
									},
									{
										state: true,
										val: 33554432,
										title: LANGUAGE.ASSET_ALARM_MSG28, //harshAcc
									},
									{
										state: true,
										val: 2097152,
										title: LANGUAGE.ASSET_ALARM_MSG29, //harshBrk
									},
								];
							}
							break;

						case 3:     // loc8
							if(assetType === 'boat' || assetType === 'jetski'){
								ret = [
									{
										state: true,
										val: 131072,
										title: userAlarmSettings && userAlarmSettings.Input1High ? userAlarmSettings.Input1High : LANGUAGE.ASSET_ALARM_MSG02, //customAlarm
									},
									{
										state: true,
										val: 32768,
										title: LANGUAGE.ASSET_ALARM_MSG11, //accOn
									},
									{
										state: true,
										val: 65536,
										title: LANGUAGE.ASSET_ALARM_MSG10, //accOff
									},
									{
										state: true,
										val: 1048576,
										title: LANGUAGE.ASSET_ALARM_MSG03, //Shore Power Disconnect
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG09, //power
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
								]
							}else{
								ret = [
									{
										state: true,
										val: 131072,
										title: userAlarmSettings && userAlarmSettings.Input1High ? userAlarmSettings.Input1High : LANGUAGE.ASSET_ALARM_MSG25, //input
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 256,
										title: LANGUAGE.ASSET_ALARM_MSG07, //tilt
									},
									{
										state: true,
										val: 65536,
										title: LANGUAGE.ASSET_ALARM_MSG10, //accOff
									},
									{
										state: true,
										val: 32768,
										title: LANGUAGE.ASSET_ALARM_MSG11, //accOn
									},
									{
										state: true,
										val: 16384,
										title: LANGUAGE.ASSET_ALARM_MSG08, //impact
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG09, //power
									},
									{
										state: true,
										val: 262144,
										title: userAlarmSettings && userAlarmSettings.Input2 ? userAlarmSettings.Input2 : LANGUAGE.ASSET_ALARM_MSG34, //positive input on
									},
									{
										state: true,
										val: 1048576,
										title: LANGUAGE.ASSET_ALARM_MSG35, //positive input off
									},
								];
							}

							break;
						default:    //protect
							if(assetType === 'boat' || assetType === 'jetski'){
								ret = [
									{
										state: true,
										val: 131072,
										title: userAlarmSettings && userAlarmSettings.Input1High ? userAlarmSettings.Input1High : LANGUAGE.ASSET_ALARM_MSG02, //customAlarm
									},
									{
										state: true,
										val: 32768,
										title: LANGUAGE.ASSET_ALARM_MSG11, //accOn
									},
									{
										state: true,
										val: 65536,
										title: LANGUAGE.ASSET_ALARM_MSG10, //accOff
									},
									{
										state: true,
										val: 1048576,
										title: LANGUAGE.ASSET_ALARM_MSG03, //Shore Power Disconnect
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG09, //power
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
								]
							}else if(solutionType && solutionType.toLowerCase() === 'witiprotect' ||
								solutionType && solutionType.toLowerCase() === 'witiqprotect'){
								ret = [
									{
										state: true,
										val: 131072,
										title: LANGUAGE.ASSET_ALARM_MSG39, //negative input,  witi alarm
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 16384,
										title: LANGUAGE.ASSET_ALARM_MSG08, //impact
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG09, //power
									},
								];
							}else{
								ret = [
									{
										state: true,
										val: 131072,
										title: userAlarmSettings && userAlarmSettings.Input1High ? userAlarmSettings.Input1High : LANGUAGE.ASSET_ALARM_MSG25, //input
									},
									{
										state: true,
										val: 1024,
										title: LANGUAGE.ASSET_ALARM_MSG05, //geolock
									},
									{
										state: true,
										val: 256,
										title: LANGUAGE.ASSET_ALARM_MSG07, //tilt
									},
									{
										state: true,
										val: 65536,
										title: LANGUAGE.ASSET_ALARM_MSG10, //accOff
									},
									{
										state: true,
										val: 32768,
										title: LANGUAGE.ASSET_ALARM_MSG11, //accOn
									},
									{
										state: true,
										val: 16384,
										title: LANGUAGE.ASSET_ALARM_MSG08, //impact
									},
									{
										state: true,
										val: 512,
										title: LANGUAGE.ASSET_ALARM_MSG17, //lowBattery
									},
									{
										state: true,
										val: 4,
										title: LANGUAGE.ASSET_ALARM_MSG09, //power
									},
								];
							}

					}
				}
				if (ret.length) {
					if(solutionType && solutionType.toLowerCase() === 'witiprotect' ||
						solutionType && solutionType.toLowerCase() === 'wititrack' ||
						solutionType && solutionType.toLowerCase() === 'witiqprotect'){
						if(this.isPositiveInputSupported){
							ret.push({
								state: true,
								val: 1048576,
								title: LANGUAGE.ASSET_ALARM_MSG43, //witi disarmed
							},{
								state: true,
								val: 262144,
								title: LANGUAGE.ASSET_ALARM_MSG42, //witi armed
							})
						}
					}

					ret.sort(function(a,b){
						if(a.title.toLowerCase() < b.title.toLowerCase()) return -1;
						if(a.title.toLowerCase() > b.title.toLowerCase()) return 1;
						return 0;
					});
				}
				return ret;
			},
			saveAlarmOptions: function(data, url){
				var self = this;

				self.$app.dialog.progress();
				self.$app.request.post(url, data, function (result, xhr, status) {
					//console.log(result);
					if (result.MajorCode == '000') {
						if (result.MinorCode == '1006') {
							self.$app.methods.customDialogNoCredit();
						}else{
						
							self.updateAlarmOptions(data);
							self.$app.methods.checkBalance();

							if (leftView.router.history && leftView.router.history.length && leftView.router.history[leftView.router.history.length-2].indexOf('/asset-select/multiple/asset-alarm/') != -1) {
								leftView.router.back('/panel-left/', {force:true});
							}else{
								leftView.router.back();
							}
						}
					}else if(result.MajorCode == '100' && result.MinorCode == '1006'){
						self.$app.methods.customDialogNoCredit();
					}else if(result.MajorCode == '100' && result.MinorCode == '1003'){
						app.methods.customDialog({title: LANGUAGE.PROMPT_MSG050, text: LANGUAGE.PROMPT_MSG051});
					}else{
						self.$app.methods.customNotification({
							hold: 5000,
							title: LANGUAGE.COM_MSG16
						});
						self.$app.methods.checkBalance();
					}
					self.$app.utils.nextFrame(() => {
						self.$app.dialog.close();
					});

				},
				function (xhr, status) {
					self.$app.utils.nextFrame(() => {
						self.$app.dialog.close();
					});

					self.$app.dialog.alert('Error occured at Save AlarmOpitons');
				},
				'json');
			},
			updateAlarmOptions: function(params){
				var self = this;
				var IMEIList = params.imeis.split(',');
				var assetList = self.$app.methods.getFromStorage('assetList');

				if (IMEIList.length) {
					$.each(IMEIList, function(index, value){
						assetList[value].AlarmOptions = params.alarmOptions;
						if (params.SpeedingMode == 2) {
							assetList[value].MaxSpeed = params.MaxSpeed;
						}
					});
				}

				self.$app.methods.setAssetList({objects: assetList});
			},
			showPromptSetOverspeedVal: function(OverspeedTypesEl){
				let self = this;

				var text = `
					<div class="custom-modal-text">${ LANGUAGE.PROMPT_MSG096 }(${Protocol.Helper.getSpeedUnit(self.MaxSpeedUnit)}):</div>
					<div class="dialog-input-field item-input">
						<div class="item-input-wrap">
							<input type="text" class="dialog-input" name="MaxSpeed" value="${ self.MaxSpeed }">
						</div>
					</div>
				`;

				app.dialog.create({
				    title: '<div class="custom-modal-logo-wrapper"><img class="custom-modal-logo" src="'+ app.data.AppDetails.logoModal +'" alt=""/></div>',
				    text: text,
				    buttons: [
				    	{
				    		text: LANGUAGE.COM_MSG01,
				    		cssClass: 'color-black',
                            onClick: function(dialog){
                            	if (OverspeedTypesEl) {
                            		for (var i = OverspeedTypesEl.length - 1; i >= 0; i--) {
                            			if (OverspeedTypesEl[i].value == '1') {
		                                    OverspeedTypesEl[i].checked = true;
		                                    break;
		                                }
                            		}
                            	}
                            }
				    	},
				      	{
                            text: LANGUAGE.COM_MSG12,
                            cssClass: 'color-red',
                            onClick: function(dialog){
                            	let MaxSpeed = dialog.$el.find('input[name="MaxSpeed"]').val();

                                self.$setState({
                                	MaxSpeed: MaxSpeed ? MaxSpeed : 1
                                })

                            }
                        },
				    ],
				}).open();
			}

		},

		on: {
			pageInit: function (e, page) {
				var self = this;
				var form = page.$el.find('[name = "AssetAlarmForm"]');
				form.on('submit', function(e){ 
					e.preventDefault();
					var userInfo = self.$app.methods.getFromStorage('userInfo');
					var checkboxes = page.$el.find('[name = "checkbox-alarm"]');
					var offlineOptions = page.$el.find('[name = "offline-option"]');
					var url = API_URL.SET_ALARM_LOC8;
					//console.log(offlineOptions);
					var data = {
						MinorToken: userInfo.MinorToken,
						MajorToken: userInfo.MajorToken,
						imeis: self.IMEI,
						alarmOptions: 0,
					};

					for (var i = checkboxes.length - 1; i >= 0; i--) {
						if (!checkboxes[i].checked) {
							data.alarmOptions += parseInt(checkboxes[i].value, 10);
						}
					}

					self.AlarmListType = parseInt(self.AlarmListType,10);
					
					switch (self.AlarmListType){
						case 1:
							url = API_URL.SET_ALARM_PROTECT;
							break;

						case 2:
							url = API_URL.SET_ALERT_CONFIG;

							data.AlertTypes = data.alarmOptions;
							data.IsIgnore = self.IgnoreBetweenState ? 1 : 0;
							//data.IsEmailNotification = self.toggleEmailEl;
							//data.IsPushNotification = self.togglePushEl;
							
							
							if(self.ShowAdditionalBlocks){
								data.Weeks = self.DaysOfWeekSelect.$selectEl?.val()?.toString();
								data.DateFrom = moment(page.$el.find('[name="PickerStart"]').val(), 'HH:mm').utc().format('HH:mm');
								data.DateTo = moment(page.$el.find('[name="PickerEnd"]').val(), 'HH:mm').utc().format('HH:mm');
							}else{
								data.Weeks = '';
								data.DateFrom = '00:00';
								data.DateTo = '00:00';	
							}
							if (!(data.AlertTypes & 32)) {
					            data.SpeedingMode = parseInt(page.$el.find('input[name="overspeed-type"]:checked').val(),10);
					            if (data.SpeedingMode == 2) {
					                data.MaxSpeed = Protocol.Helper.getSpeedValueInKM(self.MaxSpeedUnit, self.MaxSpeed);//self.MaxSpeed;
					            }
					        }
							
							if(!self.ShowAdditionalBlocks){
								data.SpeedingMode = 1;
							}
							
					        if (!(data.AlertTypes & 67108864)) {
					        	data.OfflineHours = '';
					        	for (var i = offlineOptions.length - 1; i >= 0; i--) {
					        		if (offlineOptions[i].checked) {
					        			data.OfflineHours += offlineOptions[i].value + ',';
					        		}
					        	}
					        	if (data.OfflineHours) {
					        		data.OfflineHours = data.OfflineHours.slice(0,-1);
					        	}
					        }

							break;
					}

					//console.log(self.toggleEmailEl, self.togglePushEl)

					console.log(data, url);
					self.saveAlarmOptions(data, url);

					return false;
				});
				

				self.getAlarmOptions();

				form.on('change', '.disablingController',function(e){
					var parent = this.closest('.list');
					var elements = $$(parent).find('.disablingObj');

					for (var i = elements.length - 1; i >= 0; i--) {
						if(this.checked){
							$$(elements[i]).removeClass('disabled');
						}else{
							$$(elements[i]).addClass('disabled');
						}
					}
				});

				form.on('change', 'input[name="overspeed-type"]', function(e){
					if (e.target.value == 2) {
						self.showPromptSetOverspeedVal(form.find('input[name="overspeed-type"]'));
					}
				});

				form.on('change', 'input[name="checkbox-alarm"][value="67108864"]', function(e){
					var offlineOptionsEl = page.$el.find('input[name="offline-option"]');
					for (var i = offlineOptionsEl.length - 1; i >= 0; i--) {
						offlineOptionsEl[i].checked = this.checked;
					}
					self.$setState({
						OfflineState: this.checked
					})
				});

				form.on('change', 'input[name="offline-option"]', function(e){
					var offlineOptionsEl = page.$el.find('input[name="offline-option"]');
					var oneSelected = false;
					for (var i = offlineOptionsEl.length - 1; i >= 0; i--) {
						if (offlineOptionsEl[i].checked) {
							oneSelected = true;
						}
					}
					if (!oneSelected) {
						this.checked = true;
						self.$app.methods.customNotification({title: LANGUAGE.ASSET_ALARM_MSG32, text: LANGUAGE.PROMPT_MSG097});
					}
				});

				


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

				if (self.ToggleAllAlarms) {
					app.toggle.destroy(self.ToggleAllAlarms);
				}

				if (self.DaysOfWeekSelect) {
					self.DaysOfWeekSelect.destroy();
				}

				if (self.TimePickerStart) {
					self.TimePickerStart.destroy();
				}

				if (self.TimePickerEnd) {
					self.TimePickerEnd.destroy();
				}


				/*var toggleAll = self.$app.toggle.get('.toggle-all-alarm');
				console.log(toggleAll);*/
			},

		}
	};
</script>