<template>
<!-- Page, data-name contains page name which can be used in callbacks -->
        <div class="page " data-name="geofence"> <!-- 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">{{PageTitle}}</div>
                    <div class="right">
                                        
                    </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="GroupEditForm" class="page-content under-development">
                
                <input type="hidden" name="Code" value="{{Code}}">

                <input type="submit" id="submit-form" class="display-none" />
                <div class="list margin-top-0 ">
                    <ul>
                        <li>
                            <a class="item-link smart-select smart-select-init custom-smart-select {{#if Code}}disabled{{/if}}" data-open-in="popover" data-close-on-select="true">
                                <select name="GeofenceType" required validate>
                                    {{#GeofenceTypes}}
                                        <option value="{{Val}}" {{#if State}} selected {{/if}}>{{Name}}</option>
                                    {{/GeofenceTypes}}                                                                  
                                </select>
                                <div class="item-content item-input">
                                    <div class="item-media text-color-lightgray">
                                       <i class="f7-icons icon-admin-geofences"></i>
                                    </div>
                                    <div class="item-inner">
                                        <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG17}}</div>                                        
                                    </div>
                                </div>
                            </a>
                        </li> 
                        <li>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <!-- <i class="f7-icons icon-admin-geofences"></i> -->
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG04}}</div>
                                    <div class="item-input-wrap">
                                        <input type="text" name="Name" placeholder="{{@global.LANGUAGE.GEOFENCES_MSG05}}" value="{{Name}}" maxlength="200" required validate>
                                    </div>
                                </div>
                            </div>
                        </li>
                 		<li class="item-content">   
                            <div class="item-media text-color-lightgray">
                                <i class="f7-icons icon-active"></i>
                            </div>                         
                            <div class="item-inner">
                                <div class="item-title">{{@global.LANGUAGE.GEOFENCES_MSG09}}</div>
                                <div class="item-after">
                                    <label class="toggle toggle-init">
                                        <input type="checkbox" name="ActiveState" {{#if ActiveState}}checked="checked"{{/if}}>
                                        <span class="toggle-icon"></span>
                                    </label>
                                </div>
                            </div>
                        </li>
                        <li>
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-address"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG06}} <i class="f7-icons text-color-gray icon-hint margin-left-4 size-14 tooltip-init" data-tooltip="{{@global.LANGUAGE.PROMPT_MSG093}}"></i></div>
                                    <div class="item-input-wrap">                                    
                                        <textarea name="Address" id="" placeholder="{{@global.LANGUAGE.GEOFENCES_MSG07}}" maxlength="400" >{{Address}}</textarea>
                                        <span class="input-search-button ">
                                            <i class="f7-icons icon-search ripple text-color-red ripple-color-red"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </li>
                        {{#js_if "this.GeofenceType == '1'"}}
                        <li key="keyRadius">
                            <div class="item-content item-input">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-radius"></i>
                                </div>
                                <div class="item-inner">
                                    <div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG07}}</div>
                                    <div class="item-input-wrap">
                                        <input type="tel" name="Radius" placeholder="{{@global.LANGUAGE.ASSET_GROUPS_MSG07}}" value="{{Radius}}" class="only_numbers"  pattern="[.0-9]*" data-error-message="{{@global.LANGUAGE.PROMPT_MSG024}}" maxlength="200"  required validate>
                                    </div>
                                </div>
                            </div>
                        </li>
                        {{/js_if}}
                        <li>
                            <a class="item-link smart-select smart-select-init custom-smart-select custom-smart-select-assets" data-open-in="popup" data-searchbar="true" data-searchbar-placeholder="{{@global.LANGUAGE.COM_MSG02}}" data-append-searchbar-not-found="{{@global.LANGUAGE.PROMPT_MSG008}}" data-page-title = "{{@global.LANGUAGE.ASSET_GROUPS_MSG08}}">
                                <select name="Assets" multiple   >
                                    {{#AssetList}}
                                        <optgroup label="{{Name}}" data-code="{{Code}}">
                                            {{#Assets}}
                                                <option value="{{IMEI}}" data-id="{{Id}}" {{#if AssetSelected}} selected {{/if}} >{{Name}}</option>
                                            {{/Assets}}
                                        </optgroup>
                                    {{/AssetList}}  
                                </select>
                                <div class="item-content item-input">
                                    <div class="item-media text-color-lightgray">
                                        <i class="f7-icons icon-name"></i>
                                    </div>
                                    <div class="item-inner">
                                        <div class="item-title item-label">{{@global.LANGUAGE.ASSET_GROUPS_MSG09}}</div>                                        
                                    </div>
                                </div>
                            </a>
                        </li>
                        <li>
                            <a class="item-link smart-select smart-select-init custom-smart-select" data-open-in="popover" >
                                <select name="AlarmType" multiple required validate>
                                    {{#AlarmType reverse="true"}}
                                        <option value="{{Val}}" {{#if State}} selected {{/if}}>{{Name}}</option>
                                    {{/AlarmType}}                                                                  
                                </select>
                                <div class="item-content item-input">
                                    <div class="item-media text-color-lightgray">
                                        <i class="f7-icons icon-admin-alarms"></i>
                                    </div>
                                    <div class="item-inner">
                                        <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG08}}</div>                                        
                                    </div>
                                </div>
                            </a>
                        </li> 
                        {{#if NotifyEmails}} 
                        <li >
                            <a class="item-link smart-select smart-select-init custom-smart-select smartSelectContacts" data-open-in="popup" data-searchbar="true" data-searchbar-placeholder="{{@global.LANGUAGE.COM_MSG02}}" data-append-searchbar-not-found="{{@global.LANGUAGE.PROMPT_MSG008}}" data-page-title = "{{@global.LANGUAGE.COM_MSG84}}">
                                <select name="NotifyEmails" multiple  >
                                    {{#NotifyEmails}}
                                        {{#if EMail}}
                                        <option value="{{Code}}" {{#if Selected}} selected {{/if}}>{{EMail}}({{FullName}})</option>
                                        {{/if}}
                                    {{/NotifyEmails}}  
                                </select>
                                <div class="item-content item-input">
                                    <div class="item-media text-color-lightgray">
                                        <i class="f7-icons icon-email"></i>
                                    </div>
                                    <div class="item-inner">
                                        <div class="item-title item-label">{{@global.LANGUAGE.GEOFENCES_MSG14}}</div>                                        
                                    </div>
                                </div>
                            </a>
                        </li>
                        {{else}}
                        <li key="PreloaderIntervalServicesList">
                            <div  class="item-content">
                                <div class="item-media text-color-lightgray">
                                    <i class="f7-icons icon-email"></i>
                                </div>
                                <div class="item-inner">
                                    <div  class="item-title text-align-center">
                                        <div class="preloader color-red"></div>
                                    </div> 
                                </div>
                            </div>
                        </li>
                        
                        {{/if}}

                                              
                       
                  
                    </ul>
                </div>

                <div class="list no-hairlines">
                    <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>              
				
            </form>

        </div>
    </template>


<script>
  // script must return component object
    return {
        data: function () {
            var self = this;
            //var assetList = self.$app.methods.getAssetsByGroups({NoGroupToBottom: true});

            //console.log(assetList);
            var ret = {
                PageTitle: self.$route.query.code ? LANGUAGE.COM_MSG73 : LANGUAGE.GEOFENCES_MSG03,
                Code: self.$route.query.code,
                //AssetList: assetList, 
                AssetList: [],                 
                Name: '',
                Address: '',
                Radius: 200,
                ActiveState: false,
                AlarmType: Protocol.Helper.getGoefenceAlarmTypes(),
                GeofenceTypes: Protocol.Helper.getGeofenceTypes(),
                GeofenceType: 1, //circle

                IgnoreBetweenState: false,
                TimePickerStart: false,
                TimePickerEnd: false,
                DaysOfWeekSelect: false,
                DaysOfWeek: [],

                GroupRadius: false,
                GroupMarkers: false,
                
            };      
            
            return ret;
        },
        methods: {
            initIgnoreBetweenBlock: function(params = {}){
                let self = this;    

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

                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 = Protocol.Helper.getWeekArray();

                if (!StartTimeValArray || !StartTimeValArray.length) {
                    StartTimeValArray = ['19', '00'];
                }
                if (!EndTimeInputArray || !EndTimeInputArray.length) {
                    EndTimeInputArray = ['06', '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,
                    IgnoreBetweenState: params.IgnoreBetweenState ? true : false,
                });

                self.DaysOfWeekSelect = app.smartSelect.create({
                    el: daysOfWeekEl,
                    openIn: 'popover',
                });
                
            
            },
            onMapClick: function (e) {
                var self = this;
                self.GroupRadius.setLatLng(e.latlng);   
                //self.getPointsInCircle(self.GroupRadius);

                self.updateGeofenceAddress(e.latlng);     
            },
            updateGeofenceAddress: function(latlng){
                var self = this;
                app.progressbar.show();
                Protocol.Helper.getAddressByGeocoder(latlng,function(address){

                    self.$app.utils.nextTick(()=>{
                        app.progressbar.hide();    
                    }, 300);
                            
                  
                    self.$setState({
                        Address: address,
                    });
                }); 
            },
            centeringMap: function(params){
            	var self = this;
                if (params && params.onlyAddress) {
                    MapTrack.fitBounds([self.GroupRadius.getBounds()],{padding:[16,16]});
                }else if(params && params.onlyAssets && self.GroupMarkers && self.GroupMarkers.getLayers().length > 0){
                    MapTrack.fitBounds([self.GroupMarkers.getBounds()],{padding:[16,16]});
                }else{
                    if (self.GroupMarkers && self.GroupMarkers.getLayers().length > 0) { 
                        MapTrack.fitBounds([self.GroupMarkers.getBounds(),self.GroupRadius.getBounds()],{padding:[16,16]});
                    } else{                    	
                        MapTrack.fitBounds([self.GroupRadius.getBounds()],{padding:[16,16]});
                    }
                }
                    
            },	
            updateGroupMarkers: function (assets){
                var self = this;
                if (self.GroupMarkers) {
                    self.GroupMarkers.clearLayers();
                    if (MapTrack) {
                        MapTrack.removeLayer(self.GroupMarkers);
                    }        
                }
                self.GroupMarkers = L.markerClusterGroup({'maxClusterRadius':35,}); 
                if (assets && assets.length > 0) {
                    var point = '';
                    var markerData = '';                    
                    for (var i = assets.length - 1; i >= 0; i--) {
                    	point = ''; 
                        markerData = '';
                        if (POSINFOASSETLIST[assets[i]] && POSINFOASSETLIST[assets[i]].posInfo && POSINFOASSETLIST[assets[i]].posInfo.lat !== 0 && POSINFOASSETLIST[assets[i]].posInfo.lng !== 0) {               
                            point = L.marker([POSINFOASSETLIST[assets[i]].posInfo.lat,POSINFOASSETLIST[assets[i]].posInfo.lng], {icon: Protocol.MarkerIcon[2]}); 
                            markerData = POSINFOASSETLIST[assets[i]].Name ? POSINFOASSETLIST[assets[i]].Name : POSINFOASSETLIST[assets[i]].IMEI;
                            point.bindTooltip(markerData,{permanent: false, direction: 'right'});
                            point.addTo(self.GroupMarkers);
                        }                    	
                    }
                    self.GroupMarkers.addTo(MapTrack);

                    self.centeringMap();                    
                    
                } 
            },







            saveGeofence: function(data, url){
                var self = this;

                self.$app.preloader.show();
                self.$app.request.post(url, data, function (result, xhr, status) { 
                                   
                    console.log(result);
                    if (result && result.MajorCode == '000') {
                        self.$app.preloader.hide(); 
                        leftView.router.back();
                                 
                    }else{
                        self.$app.preloader.hide(); 
                        self.$app.dialog.alert('Something wrong');                
                    }
                    
                },
                function (xhr, status) {            
                    self.$app.preloader.hide();
                    self.$app.dialog.alert('Error occured at Save Geofence details');                
                },
                'json');  
            },
            
            getPointsInCircle: function (circle) {
                var self = this;
                if (AllMarkersGroup && circle !== undefined) {                    
                    var circle_lat_long = circle.getLatLng();

                    var pointsInCircle = [];                    
                    
                    AllMarkersGroup.eachLayer(function(layer) {                        
                        var distance_from_layer_circle = layer.getLatLng().distanceTo(circle_lat_long);
                        
                        if (distance_from_layer_circle <= circle.getRadius()) {                            
                            if (layer._custom_asset_imei) {
                                pointsInCircle.push(layer._custom_asset_imei);
                            }
                        }
                    });
                
                    var select = self.$el.find('select[name="Assets"]'); 
                    var notInGroupAssetsGroup = select.find('optgroup[data-code="000000"]');  
                    if (notInGroupAssetsGroup && notInGroupAssetsGroup.length) {
                        notInGroupAssetsGroup.find("option").prop('selected', false);
                    }   
                    if (pointsInCircle.length) {
                        $.each(pointsInCircle, function(key, val){
                            //check is the asset in any group if not then select this asset
                            notInGroupAssetsGroup.find('option[value="'+val+'"]').prop('selected', true); 
                        });
                    } 
                    select.change(); 
                    
                }       
            },	

            getEmailList: function(){
                let self = this;  
                let userInfo = self.$app.methods.getFromStorage('userInfo'); 
                
                self.$app.request.post(API_URL.GET_CONTACT_USERS_LIST, {MajorToken: userInfo.MajorToken}, function (result, xhr, status) {                    
                    if (result && result.length) {
                        let contactList = self.$app.methods.sortContactList(result);
                        if (self.ContactList && self.ContactList.length) {
                            for (let i = self.ContactList.length - 1; i >= 0; i--) {
                                if (self.ContactList[i].Code) {
                                    let index = contactList.findIndex(x => x.Code==self.ContactList[i].Code);
                                    if (index != -1) {
                                        contactList[i].Selected = true;
                                    }
                                }                                
                            }
                        }
                        self.$setState({
                            NotifyEmails: contactList
                        });
                    }
                    
                },
                function (xhr, status) {          
                   
                    self.$app.dialog.alert('Error occured at Get Contact List ');                
                },
                'json');
            }
          
        },
       
        on: {
            pageInit: function (e, page) { 
                let self = this;
                let assetList = self.$app.methods.getAssetsByGroups({NoGroupToBottom: true});
                let latlng = [0, 0];
                
                let formEl = page.$el.find('[name = "GroupEditForm"]');
                let radiusEl = page.$el.find('[name="Radius"]');
                let assetsEl = page.$el.find('[name="Assets"]'); 
                let searchAddressButtonEl = page.$el.find('.input-search-button'); 
                let geofenceTypeEl = page.$el.find('[name="GeofenceType"]');

                self.getEmailList(); 
               // MapTrack.on('click', self.onMapClick);

                if (!self.Code) {
                    self.initIgnoreBetweenBlock();  
                    
                    self.$setState({
                    	AssetList: assetList,                      
                    });  

                    self.GroupRadius = L.circle(latlng, {
		                color: '#AA5959',
		                fillColor: '#FF0000',
		                fillOpacity: 0.25,
		                radius: self.Radius,
		            }).addTo(MapTrack);                 
                }else{
                    let geofenceList = self.$app.methods.getFromStorage('geofenceList');
                    let geofence = geofenceList[self.Code];
                    let weeks = '';
                    latlng = [geofence.Lat, geofence.Lng];
                    
                    if (geofence.Week && geofence.Week.length) {
                        for (let i = geofence.Week.length - 1; i >= 0; i--) {
                            weeks += geofence.Week[i].Week+',';
                        }
                        weeks.slice(0, -1);
                    }                    

                    if (geofence.SelectedAssetList && geofence.SelectedAssetList.length) {
                    	for (let i = geofence.SelectedAssetList.length - 1; i >= 0; i--) {                    		
                    		for (var y = assetList.length - 1; y >= 0; y--) {                    			
                    			if (assetList[y].Assets && assetList[y].Assets.length) {
                    				let found = assetList[y].Assets.findIndex(x => x.Id == geofence.SelectedAssetList[i].AsCode);
                    				if (found != -1) {                    					
                    					assetList[y].Assets[found].AssetSelected = true;
                    					break; 
                    				}
                    			}
                    		}
                    	}
                    }

                    self.GroupRadius = L.circle(latlng, {
		                color: '#AA5959',
		                fillColor: '#FF0000',
		                fillOpacity: 0.25,
		                radius: geofence.Radius,
		            }).addTo(MapTrack);
                  
                    self.initIgnoreBetweenBlock({
                        IgnoreBetweenState: geofence.Inverse,
                        Weeks: weeks,
                        BeginTime: weeks ? geofence.Week[0].BeginTime : '',
                        EndTime: weeks ? geofence.Week[0].EndTime : '',
                        
                    });
                    
                    self.$setState({
                        Name: geofence.Name,
                        Radius: geofence.Radius,
                        Address: geofence.Address,
                        ActiveState: geofence.State ? true : false,
                        AssetList: assetList,
                        AlarmType: Protocol.Helper.getGoefenceAlarmTypes(geofence.Alerts),
                        GeofenceTypes: Protocol.Helper.getGoefenceAlarmTypes(geofence.GeoType),
                        GeofenceType: geofence.GeoType,
                        ContactList: geofence.ContactList,
                    }); 

                    if (geofence.SelectedAssetList && geofence.SelectedAssetList.length) {
                    	let tempAssetArray = [];	                    
	                    for (var i = geofence.SelectedAssetList.length - 1; i >= 0; i--) {	                    	
	                    	tempAssetArray.push(geofence.SelectedAssetList[i].IMEI);
	                    }
                    	self.updateGroupMarkers(tempAssetArray);
                    }                  
 
                }
                
           		
                MapTrack.pm.addControls({
                    position: 'topleft',
                    drawMarker: false,
                    drawPolyline: false,
                    drawRectangle: false,
                    cutPolygon: false,
                    //drawCircle: false,
                });
                                     
                
                /*geofenceTypeEl.on('change', function(){
                    self.$setState({
                        GeofenceType: this.value
                    })
                    switch(this.value){
                        case '2':
                            

                            break;
                        default:
                            
                    }
                });*/

                /*MapTrack.on('pm:drawstart', ({ workingLayer }) => {
                  workingLayer.on('pm:vertexadded', e => {
                    console.log(1,e);
                  });
                });*/

                MapTrack.on('pm:drawstart', e => {
				  	console.log(self.GeofenceLayer);
				  	if (self.GeofenceLayer) {
				  		MapTrack.removeLayer(self.GeofenceLayer);
				  	}
				  	//e.workingLayer.clearLayers();
				});

                MapTrack.on('pm:create', e => {
                	self.GeofenceLayer = e.layer;
                		console.log(e);
                });
				

                radiusEl.on('change input', function(){
                    var value = this.value;
                    if (!value.match(/[^0-9]/g)) {
                       
                        self.GroupRadius.setRadius(value);
                        self.centeringMap();                        
                    }       
                }); 

                assetsEl.on('change', function(){
                    self.updateGroupMarkers($$(this).val());                          
                });

                searchAddressButtonEl.on('click', function(e){ 
                    var valAddress = $$(this).siblings('[name="Address"]').val();
                    if (valAddress.length >= 3) {
                        self.$app.progressbar.show();
                        Protocol.Helper.getLatLngByGeocoder(valAddress,function(coords){   
                            self.$app.utils.nextFrame(()=>{
                            	self.$app.progressbar.hide(); 
                            });
                           
                            if (coords) {                                
                                self.GroupRadius.setLatLng(coords);
                                self.centeringMap({onlyAddress:true});                             
                            }else{
                                self.$app.methods.customNotification({                                    
                                    text: LANGUAGE.PROMPT_MSG008                                   
                                });
                            }
                        });
                    }                   
                });
                
                formEl.on('submit', function(e){
                    e.preventDefault();      

                    if (self.GeofenceLayer) {
                    	var userInfo = self.$app.methods.getFromStorage('userInfo');
	                    //var latlng = self.GroupRadius.getLatLng();
	                    var latlng = self.GeofenceLayer.getLatLng();
	                    var selectedAssetsArr = assetsEl.find('option:checked');
	                    var selectedAssetIds = '';
	                    var ignoreDaysArr = formEl.find('[name="IgnoreDays"]').val();
	                    for (var i = selectedAssetsArr.length - 1; i >= 0; i--) {
	                    	selectedAssetIds += ','+$$(selectedAssetsArr[i]).data('id');
	                    }
	                    if (selectedAssetIds) {
			                selectedAssetIds = selectedAssetIds.substr(1);
			            }
			            console.log(latlng);

	                    var url = API_URL.GEOFENCE_ADD;

	                    var data = {
	                        MinorToken: userInfo.MinorToken,
	                        MajorToken: userInfo.MajorToken, 

	                        Name: formEl.find('[name="Name"]').val(),  
	                        //Lat: latlng.lat,
	                        //Lng: latlng.lng,   
	                        //Radius: self.GroupRadius.getRadius(),    
	                        Alerts: formEl.find('[name="AlarmType"]').val().toString(),  
	                        Address: formEl.find('[name="Address"]').val(),   
	                        AssetCodes: selectedAssetIds,
	                        ContactCodes: formEl.find('[name="NotifyEmails"]').val().toString(),
	                        
	                        AlertConfigState: formEl.find('[name="ActiveState"]').is(":checked") ? 1 : 0,

	                        Inverse: formEl.find('[name="IgnoreBetweenState"]').is(":checked") ? 1 : 0,
	                        BeginTime: moment(formEl.find('[name="PickerStart"]').val(), 'HH:mm').utc().format('HH:mm:ss'),
	                        EndTime: moment(formEl.find('[name="PickerEnd"]').val(), 'HH:mm').utc().format('HH:mm:ss'),

	                        DelayTime: 0,  
	                        GeoType: geofenceTypeEl.val(), 
	                        
	                    };

	                    if (ignoreDaysArr && ignoreDaysArr.length) {
	                        data.Days = ignoreDaysArr.toString();
	                    }

	                    if (self.Code) {
	                    	data.Code = self.Code;
	                        url = API_URL.GEOFENCE_EDIT;
	                    }

	                    console.log(data);

	                    //self.saveGeofence(data, url);
                    }else{
                    	self.$app.methods.customDialog({text:LANGUAGE.PROMPT_MSG0102});
                    }              
	                    

                    
                    
                    return false;
                }); 
                
   
               
            }, 
            pageBeforeIn: function(e, page){
                var self = this;
                let fabViewAll = $$('.fab-viewall');  
                MapTrack.removeLayer(AllMarkersGroup);                            
                if (fabViewAll && !fabViewAll.hasClass('disabled')) {
                    fabViewAll.addClass('disabled');
                }   
            },
           	pageBeforeOut: function(e, page){
           		var self = this;
           		MapTrack.pm.removeControls();
           		if (self.GeofenceLayer) {
					MapTrack.removeLayer(self.GeofenceLayer);
				}
           	},
            pageAfterOut: function (e, page) {
                var self = this;
               // MapTrack.off('click', self.onMapClick);
                if (self.GroupRadius) {
                    MapTrack.removeLayer(self.GroupRadius);
                }                
                if (self.GroupMarkers) {
                    self.GroupMarkers.clearLayers();
                    if (MapTrack) {
                        MapTrack.removeLayer(self.GroupMarkers);
                    }        
                }

                

                var fabViewAll = $$('.fab-viewall');
                if (MapTrack && !MapTrack.hasLayer(AllMarkersGroup)) {
                    if (AllMarkersGroup.getBounds().isValid()) {  
                        MapTrack.fitBounds(AllMarkersGroup.getBounds(),{padding:[16,16]});                 
                        AllMarkersGroup.addTo(MapTrack);
                    }
                    
                    if (fabViewAll && fabViewAll.hasClass('disabled')) {
                        fabViewAll.removeClass('disabled');
                    }
                }

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

        }
    };
</script>