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

                    <a href="#" class="link icon-only filterMenuOpen">
                        <i class="f7-icons icon-filter size-18"></i>
                    </a>

                </div>
            </div>
        </div>

        <div class="toolbar tabbar tabbar-custom toolbar-top">
            <div class="toolbar-inner">
                <a href="#drivers" class="tab-link tab-link-active">
                    {{@global.LANGUAGE.JOB_DESPATCH_MSG02}}
                </a>
                <a href="#tasks" class="tab-link">
                    {{@global.LANGUAGE.JOB_DESPATCH_MSG05}}
                </a>
                <a href="#templates" class="tab-link">
                    {{@global.LANGUAGE.JOB_DESPATCH_MSG06}}
                </a>
            </div>
        </div>
        {{#js_if 'this.CurrentTab !== "tasks"'}}
        <div class="bottom-section-wrapper {{ToolbarAdditionaClass}} toolbar-bottom  bg-color-white">
            <div
                class="display-flex flex-direction-column  bottom-section-button-wrapper    justify-content-space-evenly">
                {{#js_if 'this.CurrentTab === "drivers"'}}
                <a class="col  link button button-fill color-black elevation-2 addTemplate">
                    <i class="f7-icons icon-header-added"></i>
                    {{@global.LANGUAGE.JOB_DESPATCH_MSG03}}
                </a>
                <a class="col link button button-fill color-green elevation-2 createTask">
                    <i class="f7-icons icon-header-added"></i>
                    {{@global.LANGUAGE.JOB_DESPATCH_MSG04}}
                </a>

                {{else if 'this.CurrentTab === "templates"'}}
                <a data-popup=".popup-fullscreen-newtemplate"
                    class="col popup-open link button button-fill color-black elevation-2 addTemplate">
                    <i class="f7-icons icon-header-added"></i>
                    {{@global.LANGUAGE.JOB_DESPATCH_MSG03}}
                </a>
                {{else}}

                {{/js_if}}

            </div>
        </div>
        {{/js_if}}
        <!--<div class="searchbar-backdrop"></div>-->
        <div class="tabs-animated-wrap">
            <div class="tabs">
                <div class="page-content  page-content-driver tab tab-active" id="drivers">

                    <form class="searchbar searchbar-drivers overflow-hidden">
                        <div class="searchbar-inner">
                            <div class="searchbar-input-wrap">
                                <input type="search" placeholder="{{@global.LANGUAGE.COM_MSG02}}"
                                    title="{{@global.LANGUAGE.COM_MSG02}}">
                                <i class="searchbar-icon"></i>
                                <span class="input-clear-button"></span>
                            </div>
                            <span class="searchbar-disable-button text-color-gray">{{@global.LANGUAGE.COM_MSG01}}</span>
                        </div>
                    </form>

                    <div class="block searchbar-not-found">
                        <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG008}}</div>
                    </div>


                    {{#if isDriversLoaded}}
                    <div
                        class="list media-list virtual-list no-chevron no-margin-top no-hairline-bottom searchbar-found driversList">
                        <!-- keep it empty -->
                    </div>
                    {{else}}
                    <div key="VirtualListPreloader" class="block block-strong text-align-center">
                        <div class="preloader color-red"></div>
                    </div>
                    {{/if}}


                </div>

                <div class="page-content page-content-task tab" id="tasks">
                    <form class="searchbar searchbar-task overflow-hidden">
                        <div class="searchbar-inner">
                            <div class="searchbar-input-wrap">
                                <input type="search" placeholder="{{@global.LANGUAGE.COM_MSG02}}"
                                    title="{{@global.LANGUAGE.COM_MSG02}}">
                                <i class="searchbar-icon"></i>
                                <span class="input-clear-button"></span>
                            </div>
                            <span class="searchbar-disable-button text-color-gray">{{@global.LANGUAGE.COM_MSG01}}</span>
                        </div>
                    </form>

                    <div class="block searchbar-not-found">
                        <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG008}}</div>
                    </div>

                    {{#unless isTasksLoaded}}

                    {{/unless}}

                    <div
                        class="list media-list virtual-list no-chevron no-margin-top no-hairline-bottom searchbar-found tasksList">
                        <!-- keep it empty -->
                    </div>

                </div>
                <div class="page-content  page-content-template tab" id="templates">
                    <form class="searchbar searchbar-template overflow-hidden">
                        <div class="searchbar-inner">
                            <div class="searchbar-input-wrap">
                                <input type="search" placeholder="{{@global.LANGUAGE.COM_MSG02}}"
                                    title="{{@global.LANGUAGE.COM_MSG02}}">
                                <i class="searchbar-icon"></i>
                                <span class="input-clear-button"></span>
                            </div>
                            <span class="searchbar-disable-button text-color-gray">{{@global.LANGUAGE.COM_MSG01}}</span>
                        </div>
                    </form>

                    <div class="block searchbar-not-found">
                        <div class="block-inner">{{@global.LANGUAGE.PROMPT_MSG008}}</div>
                    </div>




                    {{#if isTemplatesLoaded}}
                    <div
                        class="list media-list virtual-list no-chevron no-margin-top no-hairline-bottom searchbar-found templateList">
                        <!-- keep it empty -->
                    </div>
                    {{else}}
                    <div key="VirtualListPreloader" class="block block-strong text-align-center">
                        <div class="preloader color-red"></div>
                    </div>
                    {{/if}}



                </div>

            </div>
        </div>

    </div>



</template>


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

            var ret = {
                CurrentTab: 'drivers',
                isDriversLoaded: false,
                isTasksLoaded: false,
                isTemplatesLoaded: false,
                VirtualDriversList: null,
                SearchbarDrivers: null,
                SearchbarTasks: null,
                VirtualTasksList: null,
                SearchbarTemplates: null,
                VirtualTemplateList: null,
                ToolbarAdditionaClass: ' toolbar-size-2',
            };

            /* ret = self.$app.methods.getFromStorage('userInfo');
             ret.TimeZoneList = Protocol.Helper.getTimezoneList(ret.TimeZoneID || ret.TimeZone);
             ret.CurrentFormButtonSubmit = 'submit-form-user';*/

            return ret;
        },

        methods: {
            initTemplateList: function (templateList) {
                let self = this;
                let listEl = self.$el.find('.templateList');


                self.VirtualTemplateList = self.$app.virtualList.create({
                    el: listEl,
                    items: templateList || [],
                    //cache: false,
                    searchAll: function (query, items) {
                        var found = [];

                        query = query.trim().toLowerCase();
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].FullName.toLowerCase().indexOf(query) >= 0 ||
                                items[i].EMail.toLowerCase().indexOf(query) >= 0 ||
                                query === '') found.push(i);
                        }

                        return found; //return array with mathced indexes
                    },
                    height: function (item) {
                        return self.$app.theme === 'ios' ? 75.75 : 81.3
                    },
                    renderItem: function (item, index) {

                        let jobType = Protocol.Helper.getJobTypeByNumber(item.JobType);

                        let ret = `
                            <li data-code="${item.ID}">`;
                        ret += ` <div class="item-content">
    
                                                <div class="item-media">
                                                    <div class="user-icon text-align-center text-color-white   bg-color-red   display-flex align-items-center justify-content-center text-transform-uppercase">
                                                        ${item.TemplateName[0]}
                                                    </div>

                                                </div>
                                    <div class="item-inner">
                                        <div class="item-title-row">
                                                <div class="item-title weight-500 text-color-black text-transform-uppercase">
                                                   
                                                    ${item.TemplateName}
                                                </div>
                                                <div class="item-after">
                                                    <a href="#"   class="link ripple-color-red bigger-touch-area templateMenu"><i class="f7-icons icon-menu-asset size-18"></i></a>
                                                </div>
                                        </div>
                                        <div class="divider"></div>
                                        <div class="item-text">
                                                <div class="row no-gutter">
                                                    <div class="col-100 white-space-no-wrap" title="    ${item.TemplateName}">
                                                        <i class="f7-icons size-16 icon-input asset_list_icon text-color-lightgray vertical-middle"></i>
                                                        <span class="size-14 vertical-middle"> ${jobType.name}</span>
                                                    </div>
                                                   
                                                </div>
                                            </div>       
                                    </div>
                                 
                            </li>`;
                        return ret;
                    },
                    emptyTemplate: `<li class="item-content">${LANGUAGE.COM_MSG139}</li>`
                });

                self.$setState({
                    isTemplatesLoaded: true
                });
                self.initSearchTemplates();
            },
            initSearchTemplates: function () {
                let self = this;

                self.SearchbarTemplates = self.$app.searchbar.create({
                    el: self.$el.find('.searchbar-template'),
                    searchContainer: self.$el.find('.templateList'),
                    searchIn: '.item-inner',
                    notFoudEl: self.$el.find('.searchbar-not-found'),
                    backdrop: false
                });
            },
            initTasksList: function (taskList) {
                let self = this;
                let listEl = self.$el.find('.tasksList');


                self.VirtualTasksList = self.$app.virtualList.create({
                    el: listEl,
                    items: taskList || [],
                    //cache: false,
                    searchAll: function (query, items) {
                        var found = [];

                        query = query.trim().toLowerCase();
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].Task.TaskName.toLowerCase().indexOf(query) >= 0 ||

                                query === '') found.push(i);
                        }

                        return found; //return array with mathced indexes
                    },
                    height: function (item) {
                        return self.$app.theme === 'ios' ? 75.75 : 81.3
                    },
                    renderItem: function (item, index) {
                        // console.log(item)
                        var contactList = self.$app.methods.getFromStorage('contactList')
                        var contact = {}

                        var  StartDateTime = item.Task.StartDate ? moment.utc(item.Task.StartDate).format('MMMM DD YYYY, HH:mm') : ''
 
                        
                        let ret = `
                            <li   data-index="${index}" data-code="${item.Task.Code}">`;
                        ret += ` <div class="item-content">
    
                                                <div class="item-media">
                                                    <div class="user-icon text-align-center text-color-white   bg-color-red   display-flex align-items-center justify-content-center text-transform-uppercase">
                                                        ${item.Task.TaskName[0]}   
                                                    </div>

                                                </div>
                                    <div class="item-inner">
                                        <div class="item-title-row">
                                                <div class="item-title weight-500 text-color-black text-transform-uppercase">
                                                    <div class="item-header text-transform-capitalize" title="Task ID"></div>
                                                    ${item.Task.TaskName}
                                                </div>
                                                <div class="item-after">
                                                    <a href="#"   class="link ripple-color-red bigger-touch-area taskMenu"><i class="f7-icons icon-menu-asset size-18"></i></a>
                                                </div>
                                        </div>
                                        <div class="divider"></div>
                                        <div class="item-text">
                                                <div class="row no-gutter">
                                                    <div class="col-100 white-space-no-wrap" title=" ">
                                                        <i class="f7-icons size-16 icon-input asset_list_icon text-color-red vertical-middle"></i>
                                                        <span class="size-14  text-color-red vertical-middle">New</span>
                                                    </div>`
                        if (item.Task.DriverCode) {
                            if (item.Task.DriverCode) {
                                contact = contactList.find(obj => obj.Code === item.Task.DriverCode)
                            }
                            ret += `<div class="col-100 white-space-no-wrap" title="">
                                                        <i class="f7-icons size-16 icon-profile-name asset_list_icon text-color-lightgray vertical-middle"></i>
                                                        <span class="size-14 vertical-middle">
                                                            ${contact.FirstName} ${contact.SubName}</span>
                                                        </div>`
                        }

                        if (item.Task.StartDate) {
                            ret += `<div class="col-100 white-space-no-wrap" title=" ">
                                                        <i class="f7-icons size-16 icon-date  asset_list_icon text-color-lightgray vertical-middle"></i>
                                                        <span class="size-14 vertical-middle"> 
                                                            ${StartDateTime}    
                                                        </span>
                                                    </div>`
                        }

                        ret += `</div>
                                            </div>       
                                    </div>
                                 
                            </li>`;
                        return ret;
                    },
                    emptyTemplate: `<li class="item-content">${LANGUAGE.COM_MSG139}</li>`
                });

                self.$setState({
                    isTasksLoaded: true
                });
                self.initSearchTasks();
            },
            initSearchTasks: function () {
                let self = this;

                self.SearchbarTasks = self.$app.searchbar.create({
                    el: self.$el.find('.searchbar-task'),
                    searchContainer: self.$el.find('.tasksList'),
                    searchIn: '.item-inner',
                    notFoudEl: self.$el.find('.searchbar-not-found'),
                    backdrop: false
                });
            },
            initDriversList: function (driverList) {
                let self = this;
                let listEl = self.$el.find('.driversList');

                self.VirtualDriversList = self.$app.virtualList.create({
                    el: listEl,
                    items: driverList || [],
                    //cache: false,
                    searchAll: function (query, items) {
                        var found = [];

                        query = query.trim().toLowerCase();
                        for (var i = 0; i < items.length; i++) {
                            if (items[i].FullName.toLowerCase().indexOf(query) >= 0 ||
                                items[i].EMail.toLowerCase().indexOf(query) >= 0 ||
                                query === '') found.push(i);
                        }

                        return found; //return array with mathced indexes
                    },
                    height: function (item) {
                        return self.$app.theme === 'ios' ? 75.75 : 81.3
                    },
                    renderItem: function (item, index) {

                        let ret = `
                            <li data-code="${item.Code}" data-index="${index}" groupItemWrapper>`;
                        ret += ` <a href="#" class="item-content link groupDriverItem">
    
                                                <div class="item-media">
                                                    <div class="user-icon text-align-center text-color-white   bg-color-red   display-flex align-items-center justify-content-center text-transform-uppercase">
                                                       ${item.FirstName[0]}  ${item.SubName[0]}  
                                                    </div>

                                                </div>
                                    <div class="item-inner">
                                        <div class="item-title-row">
                                                <div class="item-title weight-500 text-color-black text-transform-uppercase">
                                                    <div class="item-header text-transform-capitalize" title="Driver">Driver</div>
                                                    ${item.FullName}
                                                </div>
                                                <div class="item-after">
                                                    <i class="f7-icons icon-arrow2 text-color-lightgray size-18"></i> 
                                                </div>
                                        </div>
                                        <div class="divider"></div>
                                        <div class="item-text">
                                                <div class="row no-gutter">
                                                    <div class="col-100 white-space-no-wrap" title="${item.FirstName} ${item.SubName}">
                                                        <i class="f7-icons size-16 icon-profile-name asset_list_icon text-color-lightgray vertical-middle"></i>
                                                        <span class="size-14 vertical-middle">${item.FirstName} ${item.SubName}</span>
                                                    </div>
                                                    <div class="col-100 white-space-no-wrap" title="${item.EMail}">
                                                        <i class="f7-icons size-16 icon-email asset_list_icon text-color-lightgray vertical-middle"></i>
                                                        <span class="size-14 vertical-middle">${item.EMail}</span>
                                                    </div>
                                                </div>
                                            </div>       
                                    </div>
                                 </a>
                            </li>`;
                        return ret;
                    },
                    emptyTemplate: `<li class="item-content">${LANGUAGE.COM_MSG139}</li>`
                });

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

                self.SearchbarDrivers = self.$app.searchbar.create({
                    el: self.$el.find('.searchbar-driver'),
                    searchContainer: self.$el.find('.driversList'),
                    searchIn: '.item-inner',
                    notFoudEl: self.$el.find('.searchbar-not-found'),
                    backdrop: false
                });
            },



         

            getContactList: function (MajorToken) {
                var self = this;

                self.$app.request.post(API_URL.GET_CONTACT_USERS_LIST, { MajorToken }, function (result, xhr, status) {
                    self.$app.preloader.hide();

                    if (result && result.length) {
                        self.$app.methods.setInStorage({ name: 'contactList', data: result });
                        var contactList = self.$app.methods.sortContactList(result);




                        self.$setState({
                            isDriversLoaded: true,
                        });
                        self.$app.utils.nextFrame(() => {
                            self.initDriversList(contactList)
                        });


                    }

                },
                    function (xhr, status) {
                        self.$app.preloader.hide();
                        self.$app.dialog.alert('Error occured at Get Contact List ');
                    },
                    'json');



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


                var data = {
                    CustomerCode: self.$root.MajorToken,
                };

                //  let url = 'https://testapi.quiktrak.co/DriverJob/V1/Jobs/TemplateGetList?CustomerCode=d0e0c662-a9d0-4b3e-8f8c-954273f0db96'




                self.$app.request.get(API_URL.GET_TEMPLATES_LIST, data, function (result, xhr, status) {

                    if (result && result.MajorCode === '000') {


                        self.$setState({
                            isTemplatesLoaded: true,
                        });
                        self.$app.utils.nextFrame(() => {
                            self.initTemplateList(result.Data)
                        });

                        self.$app.methods.setInStorage({ name: 'templateList', data: result.Data });


                    }
                },
                    function (xhr, status) {
                        console.log('Error occured doring  get templates list');

                    },
                    'json');
            },
            deleteTask: function (code) {
                var self = this;
                let url = API_URL.TASK_DELETE + '?Code=' + code

                if (code) {
                    var task = self.VirtualTasksList.items.find(obj => obj.Task.Code == code);
                    var text = LANGUAGE.JOB_DESPATCH_MSG42 + ' ' + task.Task.TaskName + '.' + ' ' + LANGUAGE.PROMPT_MSG022;
                    self.$app.dialog.confirm(text,
                        function () {


                            self.$app.preloader.show();
                            self.$app.request.post(url, function (result = {}, xhr, status) {
                                self.$app.preloader.hide();

                                if (result.MajorCode == '000') {

                                    self.$app.methods.customNotification({ title: task.Task.TaskName, text: LANGUAGE.JOB_DESPATCH_MSG43 });
                                    leftView.router.refreshPage();
                                } else {
                                    self.$app.dialog.alert('Something wrong');
                                }

                            },
                                function (xhr, status) {
                                    self.$app.preloader.hide();
                                    self.$app.dialog.alert('Error occured at TASK_DELETE');
                                },
                                'json');
                        }
                    );

                }
            },
            deleteTemplate: function (code) {
                var self = this;
                if (code) {
                    var template = self.VirtualTemplateList.items.find(obj => obj.ID == code);

                    let url = API_URL.JOB_TEMPLATE_DELETE + '?ID=' + code

                    var text = LANGUAGE.JOB_DESPATCH_MSG22 + ' ' + template.TemplateName + '.' + ' ' + LANGUAGE.PROMPT_MSG022;
                    self.$app.dialog.confirm(text,
                        function () {
                            var data = {
                                MajorToken: self.$app.methods.getFromStorage('userInfo').MajorToken,
                                ID: code,
                            };

                            self.$app.preloader.show();
                            self.$app.request.post(url, function (result = {}, xhr, status) {
                                self.$app.preloader.hide();

                                if (result.MajorCode == '000') {
                                    self.$app.methods.customNotification({ title: template.TemplateName, text: LANGUAGE.JOB_DESPATCH_MSG44 });
                                    leftView.router.refreshPage();
                                } else {
                                    self.$app.dialog.alert('Something wrong');
                                }

                            },
                                function (xhr, status) {
                                    self.$app.preloader.hide();
                                    self.$app.dialog.alert('Error occured at TEMPLATE_DELETE');
                                },
                                'json');
                        }
                    );
                }
            },
            createEmptyTask: function () {
                let self = this
                var userInfo = self.$app.methods.getFromStorage('userInfo');
                var contactList = self.$app.methods.getFromStorage('contactList');
                //var taskList = self.$app.methods.getFromStorage('taskList');

                let url = API_URL.NEW_TASK + '?MajorToken=' + userInfo.MajorToken + '&MinorToken=' + userInfo.MinorToken

                let data = {
                    CustomerCode: self.$root.MajorToken,
                    TaskName: 'No name'
                }
                self.$app.request.post(url, data, function (result, xhr, status) {
                    if (result && result.MajorCode == '000') {
                        if (result.Data) {
                            self.$app.utils.nextFrame(() => {

                                
                          
                                self.$app.popup.open('.popup-fullscreen-createtask')
                                createtaskView.router.navigate({
                                    name: 'create-task',
                                    query: {
                                        code: result.Data,
                                        name: 'No Name',
                                    },
                                });
                            });
                            //leftView.router.refreshPage();
                        }
                    } else {
                        self.$app.dialog.alert('Something wrong');
                    }
                },
                    function (xhr, status) {
                        // self.$app.preloader.hide();
                        self.$app.dialog.alert('Error occured at Add New Task ');
                    },
                    'json');
            }


        },

        on: {
            pageInit: function (e, page) {
                var self = this;
                self.getTemplateList()
                self.getContactList(self.$app.data.MajorToken);

                self.$app.methods.getPOIList()
                self.$app.methods.getTaskList(self.$app.data.MajorToken)
					.then(function (taskList) {
                        self.initTasksList(taskList)
                })
          
                
                var pageTemplate = page.$el.find('.page-content-template');
                var pageTask = page.$el.find('.page-content-task');
                var pageDriver = page.$el.find('.page-content-driver');

                var createTaskButtonEl = page.$el.find('.createTask');
                var filterMenuOpenEl = page.$el.find('.filterMenuOpen');

                var contactList = self.$app.methods.getFromStorage('contactList');
                var taskList = self.$app.methods.getFromStorage('taskList');


                filterMenuOpenEl.hide()
       

                /* var passwordForm = page.$pageEl.find('[name = "user-password-form"]');*/
                var tabsEl = page.$pageEl.find('.tab');


                // var subscribedAssetsListEl = page.$el.find('.subscribedAssetsList');

                tabsEl.on('tab:show', function (page) {
                    //   console.log(this.id)
                    if (this.id === "tasks") {
                        self.$setState({
                            CurrentTab: this.id,
                        });
                       // filterMenuOpenEl.show()
                        self.VirtualTasksList?.resetFilter()
                        // self.SearchbarDrivers.clear();
                        // self.SearchbarTemplates.clear();




                    } else if (this.id === "templates") {
                        self.$setState({
                            CurrentTab: this.id,
                            ToolbarAdditionaClass: ''
                        });
                        filterMenuOpenEl.hide()
                        // self.SearchbarDrivers.clear();
                        // self.SearchbarTasks.clear();
                    } else {
                        self.$setState({
                            CurrentTab: this.id,
                            ToolbarAdditionaClass: 'toolbar-size-2'
                        });
                        filterMenuOpenEl.hide()
                        self.SearchbarTemplates.clear();
                        self.SearchbarTasks.clear();

                        let createButton = self.$el.find('.createTask');
                        let buttonAddTemplateDriver = self.$el.find('.addTemplate');


                        createButton.on('click', '.createTask', function () {
                            self.createEmptyTask()
                        })

                        buttonAddTemplateDriver.on('click', function () {
                            self.$app.popup.open('.popup-fullscreen-newtemplate')
                            newtemplateView.router.navigate({
                                name: 'new-template',
                                query: {
                                    code: ''
                                },
                            });
                        });
                    }

                    self.$setState({
                        CurrentTab: this.id
                    });


                });

                self.initSearchDrivers()
                self.initSearchTasks()
                self.initSearchTemplates()






                pageTask.on('click', '.taskMenu', function (e) {
               
                    var code = $$(e.target).closest('li').data('code');
                  

                    self.$app.popover.create({
                        backdrop: false,
                        closeByOutsideClick: true,
                        targetEl: e.target,
                        content: '<div class="popover menu-popover" >' +
                            '<div class="popover-inner">' +
                            '<div class="list rightMenuListTask">' +
                            '<ul>' +
                            '<a href="#" data-view="current" class="item-link list-button editTask popover-close"> ' + LANGUAGE.USERS_LIST_MSG01 + '</a>' +

                            '<a href="#" class="item-link list-button popover-close text-color-red ripple-color-red deleteTask" data-code="' + code + '">' + LANGUAGE.USERS_LIST_MSG02 + '</a>' +



                            '</ul>' +
                            '</div> ' +
                            '</div>' +
                            '</div>',
                        on: {
                            open: function (popover) {
                                var buttonDelete = popover.$el.find('.deleteTask');

                                buttonDelete.on('click', function () {
                                    self.deleteTask($$(this).data('code'));
                                });

                                var buttonEdit = popover.$el.find('.editTask');
                                buttonEdit.on('click', function () {


                           

                             
                                self.$app.popup.open('.popup-fullscreen-createtask')
                                createtaskView.router.navigate({
                                    name: 'create-task',
                                    query: {
                                        code: code,
                                    },
                                });

                                });

                            },
                            closed: function (popover) {
                                popover.$el.remove();
                                popover.destroy();
                            }
                        }
                    }).open();
                });

                var buttonAddTemplate = page.$el.find('.addTemplate');



                buttonAddTemplate.on('click', function () {

                    self.$app.popup.open('.popup-fullscreen-newtemplate')
                    newtemplateView.router.navigate({
                        name: 'new-template',
                        query: {
                            code: ''
                        },
                    });

                });





                pageTemplate.on('click', '.templateMenu', function (e) {
                    var code = $$(e.target).closest('li').data('code');

                    self.$app.popover.create({
                        backdrop: false,
                        closeByOutsideClick: true,
                        targetEl: e.target,
                        content: '<div class="popover menu-popover" >' +
                            '<div class="popover-inner">' +
                            '<div class="list rightMenuListTemplate">' +
                            '<ul>' +
                            '<a href="#" class="item-link editTemplate list-button  popover-close"> ' + LANGUAGE.USERS_LIST_MSG01 + '</a>' +

                            '<a href="#" class="item-link list-button popover-close text-color-red ripple-color-red deleteTemplate" data-code="' + code + '">' + LANGUAGE.USERS_LIST_MSG02 + '</a>' +



                            '</ul>' +
                            '</div> ' +
                            '</div>' +
                            '</div>',
                        on: {
                            open: function (popover) {
                                var buttonDelete = popover.$el.find('.deleteTemplate');

                                buttonDelete.on('click', function () {
                                    self.deleteTemplate($$(this).data('code'));
                                });
                                var buttonEdit = popover.$el.find('.editTemplate');
                                buttonEdit.on('click', function () {


                                    self.$app.popup.open('.popup-fullscreen-newtemplate')
                                    newtemplateView.router.navigate({
                                        name: 'new-template',
                                        query: {
                                            code: code
                                        },
                                    });

                                });


                            },
                            closed: function (popover) {
                                popover.$el.remove();
                                popover.destroy();
                            }
                        }
                    }).open();
                });





                self.$app.utils.nextTick(function () {
                    $$('.driversList').on('click', '.groupDriverItem', function (e) {
                        var code = $$(e.target).closest('li').data('code');
                        if (code) {

                            self.$app.tab.show('#tasks');

                            var taskList = self.$app.methods.getFromStorage('taskList')

                            let indexes = []

                            for (i = 0; i < taskList.length; i++) {
                                if (taskList[i].Task    .DriverCode === code) {
                                    indexes.push(i)
                                }
                            }

                            self.VirtualTasksList.filterItems(indexes)

                        }
                    })

 


                    createTaskButtonEl.on('click', function () {

                        self.createEmptyTask()
                    })

                    filterMenuOpenEl.on('click', function () {


                        //var orderBy = virtualList.$el.data('order-by');

                        var content = `<div class="popover menu-popover" >
                                      <div class="popover-inner">
                                          <div class="list filterMenuList no-hairlines no-hairlines-between">
                                              <ul>
                                                  <li class="item-divider">${LANGUAGE.ASSET_LIST_MSG09}</li>`



                        content += `<li>
                                                      <a href="#" class="item-link list-button popover-close " onclick="app.methods.sortTaskList(this);" data-sort-by="name">${LANGUAGE.ASSET_LIST_MSG10}</a>
                                                  </li>
                                                   `;


                        content += ` 
                                                  

                                              </ul>
                                          </div>
                                      </div>
                                  </div>`;

                        self.$app.popover.create({
                            backdrop: false,
                            closeByOutsideClick: true,
                            targetEl: this,
                            content: content,
                            on: {
                                opened: function (popover) {
                                    //console.log(popover);
                                },
                                closed: function (popover) {
                                    popover.destroy();
                                }
                            }
                        }).open();
                    });
                }, 600);
            },
            pageBeforeRemove: function () {

                if (this.VirtualDriversList) {
                    this.VirtualDriversList.destroy();
                }
                if (this.VirtualTasksList) {
                    this.VirtualTasksList.destroy();
                }
                if (this.VirtualTemplateList) {
                    this.VirtualTemplateList.destroy();
                }
                if (this.SearchbarDrivers) {
                    this.SearchbarDrivers.destroy();
                }
                if (this.SearchbarTasks) {
                    this.SearchbarTasks.destroy();
                }
                if (this.SearchbarTemplates) {
                    this.SearchbarTemplates.destroy();
                }
            }

        }
    };
</script>