 /*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */
jQuery.Class("CTMobileSettings_RouteAnalytics_Js",{
    editInstance:false,
    getInstance: function(){
        if(CTMobileSettings_RouteAnalytics_Js.editInstance == false){
            var instance = new CTMobileSettings_Settings_Js();
            CTMobileSettings_RouteAnalytics_Js.editInstance = instance;
            return instance;
        }
        return CTMobileSettings_RouteAnalytics_Js.editInstance;
    }
},{ 
    registerDateRangeSettings:function() {
           
           var params = {};
           params['module'] = 'CTMobileSettings';
           params['action'] = 'getListRoute';
           params['mode'] = 'gettimezone';
           AppConnector.request(params).then(
            function(data) {
              if(data){
                var Today = data.result.today; 
                var Yesterday = data.result.yesterday;
                var last7days = data.result.last7days;
                var last30days = data.result.last30days;
                var monthStartDay = data.result.monthStartDay;
                var monthEndDay = data.result.monthEndDay;
                var yearStartDay = data.result.yearStartDay;
                var yearEndDay = data.result.yearEndDay;
                var lastyearStartDay = data.result.lastyearStartDay;
                var lastyearEndDay = data.result.lastyearEndDay;

                      var today_label = app.vtranslate('Today');
                 var yesterday_label = app.vtranslate('Yesterday');
                 var last_7_days_label = app.vtranslate('Last 7 Days');
                 var last_30_days_label = app.vtranslate('Last 30 Days');
                 var this_month_label = app.vtranslate('This Month');
                 var this_year_label = app.vtranslate('This Year');
                 var last_year_label = app.vtranslate('Last Year');

                 var myranges = {};
                 myranges[today_label] = [Today,Today];
                 myranges[yesterday_label] = [Yesterday, Yesterday];
                 myranges[last_7_days_label] = [last7days, Today];
                 myranges[last_30_days_label] = [last30days, Today];
                 myranges[this_month_label] = [monthStartDay, monthEndDay];
                 myranges[this_year_label] = [yearStartDay, yearEndDay];
                 myranges[last_year_label] = [lastyearStartDay, lastyearEndDay];

                 var dateValue = last7days + ' - ' + Today;
                 jQuery('input[name="listdaterange"]').val(dateValue);

                 jQuery('input[name="listdaterange"]').daterangepicker({    locale: {
                    format: 'YYYY/MM/DD',
                    separator: " - ",
                    applyLabel: app.vtranslate("Apply"),
                    cancelLabel: app.vtranslate("Cancel"),
                    fromLabel: app.vtranslate("From"),
                    toLabel: app.vtranslate("To"),
                    customRangeLabel: app.vtranslate("Custom Range"),
                    daysOfWeek: [
                        app.vtranslate("Su"),
                        app.vtranslate("Mo"),
                        app.vtranslate("Tu"),
                        app.vtranslate("We"),
                        app.vtranslate("Th"),
                        app.vtranslate("Fr"),
                        app.vtranslate("Sa")
                    ],
                    monthNames: [
                        app.vtranslate("January"),
                        app.vtranslate("February"),
                        app.vtranslate("March"),
                        app.vtranslate("April"),
                        app.vtranslate("May"),
                        app.vtranslate("June"),
                        app.vtranslate("July"),
                        app.vtranslate("August"),
                        app.vtranslate("September"),
                        app.vtranslate("October"),
                        app.vtranslate("November"),
                        app.vtranslate("December")
                    ],
                  },
                  ranges: myranges
                });

                var dateValue = last7days + ' - ' + Today;
                 jQuery('input[name="mapdaterange"]').val(dateValue);
                 
                 jQuery('input[name="mapdaterange"]').daterangepicker({    locale: {
                    format: 'YYYY/MM/DD',
                    separator: " - ",
                    applyLabel: app.vtranslate("Apply"),
                    cancelLabel: app.vtranslate("Cancel"),
                    fromLabel: app.vtranslate("From"),
                    toLabel: app.vtranslate("To"),
                    customRangeLabel: app.vtranslate("Custom Range"),
                    daysOfWeek: [
                        app.vtranslate("Su"),
                        app.vtranslate("Mo"),
                        app.vtranslate("Tu"),
                        app.vtranslate("We"),
                        app.vtranslate("Th"),
                        app.vtranslate("Fr"),
                        app.vtranslate("Sa")
                    ],
                    monthNames: [
                        app.vtranslate("January"),
                        app.vtranslate("February"),
                        app.vtranslate("March"),
                        app.vtranslate("April"),
                        app.vtranslate("May"),
                        app.vtranslate("June"),
                        app.vtranslate("July"),
                        app.vtranslate("August"),
                        app.vtranslate("September"),
                        app.vtranslate("October"),
                        app.vtranslate("November"),
                        app.vtranslate("December")
                    ],
                  },
                  ranges: myranges
                });

                getRouteListData();

                var mapdaterange = jQuery('#mapdaterange').val();
                var mapUsers = jQuery('#mapUsers').val();
                var params = {};
                params['module'] = 'CTMobileSettings';
                params['action'] = 'getListRoute';
                params['mode'] = 'listRoute';
                params['mapdaterange'] = mapdaterange;
                params['mapUsers'] = mapUsers;
                var progressIndicatorElement = jQuery.progressIndicator({
                    'position' : 'html',
                    'blockInfo' : {
                        'enabled' : true
                    }
                });
                AppConnector.request(params).then(
                function(data) {
                    progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                    if(data){
                        $("#mapRoutes").empty().append(data.result);
                    } 
                });

                 
              }
            });


            $("#searchbox").keyup(function() {               
               var searchvalue = $('#searchbox').val();
               if (searchvalue == "") {
                    $("#result ul").empty();
               } else {
                    var listdaterange = jQuery('#listdaterange').val();
                    var listUsers = jQuery('#listUsers').val();
                    var postData = {
                    "module": app.getModuleName(),
                    "parent": app.getParentModuleName(),
                    "action": 'getListRoute',
                    "mode": "listRecord",
                    "listdaterange": listdaterange,
                    "listUsers": listUsers,
                    "searchtext":searchvalue
                    };
                
                   AppConnector.request(postData).then(
                        function(data) {
                
                        var len = data.result.length;
                        $("#result ul").empty();
                        for( var i = 0; i<len; i++){
                            $("#result ul").append("<li value='"+data.result[i]['id']+"'>"+data.result[i]['text']+"</li>");
                        }
                        // binding click event to li
                        $("#result li").bind("click",function(){
                            setText(this);
                        });
                    },function(error){
                         $("#result ul").empty();
                    });
                }
            });

    },

    registerListRouteEvent : function(){

        jQuery(document).ready(function(){
        
            var mapdaterange = jQuery('#mapdaterange').val();
            var mapUsers = jQuery('#mapUsers').val();
            var params = {};
            params['module'] = 'CTMobileSettings';
            params['action'] = 'getListRoute';
            params['mode'] = 'listRoute';
            params['mapdaterange'] = mapdaterange;
            params['mapUsers'] = mapUsers;
            var progressIndicatorElement = jQuery.progressIndicator({
                'position' : 'html',
                'blockInfo' : {
                    'enabled' : true
                }
            });
            AppConnector.request(params).then(
            function(data) {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                if(data){
                    $("#mapRoutes").empty().append(data.result);
                } 
            });
        });

        jQuery('#listUsers,#listdaterange').on('change',function(){
            getRouteListData();
        });

        jQuery('#mapUsers,#mapdaterange').on('change',function(){
            var mapdaterange = jQuery('#mapdaterange').val();
            var mapUsers = jQuery('#mapUsers').val();
            var params = {};
            params['module'] = 'CTMobileSettings';
            params['action'] = 'getListRoute';
            params['mode'] = 'listRoute';
            params['mapdaterange'] = mapdaterange;
            params['mapUsers'] = mapUsers;
            var progressIndicatorElement = jQuery.progressIndicator({
                'position' : 'html',
                'blockInfo' : {
                    'enabled' : true
                }
            });
            AppConnector.request(params).then(
            function(data) {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                if(data){
                    $("#mapRoutes").empty().append(data.result);
                } 
            });
        });
    },

    registerEventsForDownload : function(){
        jQuery('#exportascsv').on('click',function(){
            var listdaterange = jQuery('#listdaterange').val();
            var listUsers = jQuery('#listUsers').val();
            var params = {
                module: 'CTMobileSettings',
                action: 'getListRoute',
                mode: 'ExportDataCount',
                listUsers:listUsers,
                listdaterange:listdaterange
            
            };
            var progressIndicatorElement = jQuery.progressIndicator({
              'position' : 'html',
              'blockInfo' : {
               'enabled' : true
              }
            });
            AppConnector.request(params).then(function (res) {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                if(res.result['success'] > 0){
                    jQuery('#type').val('csv');
                    jQuery('#downloadForm').submit();
                }else{
                    var pparams = {
                        title : app.vtranslate('Error'),
                        text: app.vtranslate('No Data Available.'),
                        animation: 'show',
                        type: 'error'
                    };
                    Vtiger_Helper_Js.showPnotify(pparams);
                       
                }
            
            });  
            
        });

         jQuery('#exportasexcel').on('click',function(){
            var listdaterange = jQuery('#listdaterange').val();
            var listUsers = jQuery('#listUsers').val();
            var params = {
                module: 'CTMobileSettings',
                action: 'getListRoute',
                mode: 'ExportDataCount',
                listUsers:listUsers,
                listdaterange:listdaterange
            
            };
            var progressIndicatorElement = jQuery.progressIndicator({
              'position' : 'html',
              'blockInfo' : {
               'enabled' : true
              }
            });
            AppConnector.request(params).then(function (res) {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                if(res.result['success'] > 0){
                    jQuery('#type').val('excel');
                    jQuery('#downloadForm').submit();
                }else{
                    var pparams = {
                        title : app.vtranslate('Error'),
                        text: app.vtranslate('No Data Available.'),
                        animation: 'show',
                        type: 'error'
                    };
                    Vtiger_Helper_Js.showPnotify(pparams);
                       
                }
            
            });  
            
        });
    },

    /**
     * Function which will handle the registrations for the elements
     */
    registerEvents : function() {
        this.registerDateRangeSettings();
        this.registerListRouteEvent();
        this.registerEventsForDownload();
    }
});


function setText(element){
    var recordid = $(element).val();
    var value = $(element).text();
    $("#searchbox").val(value);
    $("#result ul").empty();
    
    
    getRouteListData(recordid);
    
} 


function deleteRoute(routeid) {
    var message = app.vtranslate('Are you sure want to delete this record ?');
    Vtiger_Helper_Js.showConfirmationBox({'message' : message}).then(function(data) {
        var params = {};
        params['module'] = 'CTMobileSettings';
        params['action'] = 'getListRoute';
        params['mode'] = 'deleteRoute';
        params['routeid'] = routeid;
        var progressIndicatorElement = jQuery.progressIndicator({
            'position' : 'html',
            'blockInfo' : {
                'enabled' : true
            }
        });
        AppConnector.request(params).then(
        function(data) {
            progressIndicatorElement.progressIndicator({'mode' : 'hide'});
            if(data){
                /*var tabledata = JSON.parse(data.result);
                table.rows().remove();
                table.rows.add(
                   tabledata
                ).draw();*/ 

               getRouteListData();

                var params = {
                   title : "Record deleted successfully",
                   text: 'Record deleted successfully',
                   animation: 'show',
                   type: 'info'
                };
                Vtiger_Helper_Js.showPnotify(params);
            }
        });
    });
}

function getRouteListData(recordid=''){

    var listdaterange = jQuery('#listdaterange').val();
    var listUsers = jQuery('#listUsers').val();

    var mainmodule = app.getModuleName();
    var parentmodule = app.getParentModuleName();
    var action = 'getListRoute';
    var mode = 'getlist';
    var url = "index.php?module="+mainmodule+"&parent="+parentmodule+"&action="+action+"&mode="+mode+"&listdaterange="+listdaterange+"&listUsers="+listUsers+"&recordid="+recordid;
    table = jQuery('#example1').DataTable({
      'paging'      : true,
      'lengthChange': false,
      'searching'   : false,
      'ordering'    : false,
      'info'        : true,
      'autoWidth'   : false,
      'pageLength' : 20,
      'processing': true,
      'serverSide': true,
      'serverMethod': 'post',
      'destroy': true,
      'ajax': {
          'url':url
      },
      "language": {
          "sProcessing": app.vtranslate('Processing'),
          "sEmptyTable": app.vtranslate('No data available in table'),
          "sInfo": app.vtranslate('Showing')+" _START_ "+app.vtranslate('to')+" _END_ "+app.vtranslate('of')+" _TOTAL_ "+app.vtranslate('entries'),
          "sInfoEmpty": app.vtranslate('Showing')+" 0 "+app.vtranslate('to')+" 0 "+app.vtranslate('of')+" 0 "+app.vtranslate('entries'),
          "oPaginate": {
              "sFirst": app.vtranslate('First'),   
              "sLast": app.vtranslate('Last'),  
              "sNext":   app.vtranslate('Next'), 
              "sPrevious": app.vtranslate('Previous'),
          },
      },
      "columns": [
        { "data": "deleteButton" },
        { "data": "route_name" },
        { "data": "date_of_route" },
        { "data": "assigned_to" },
        { "data": "record_type" },
        { "data": "name" },
        { "data": "route_status" },
        { "data": "notes" },
        { "data": "check_in_time" },
        { "data": "check_out_time" },
        { "data": "check_in_location" },
        { "data": "check_out_location" },
        { "data": "action" }
      ]
      });

}

