 /*+*******************************************************************************
 * 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_Settings_Js",{
    editInstance:false,
    getInstance: function(){
        if(CTMobileSettings_Settings_Js.editInstance == false){
            var instance = new CTMobileSettings_Settings_Js();
            CTMobileSettings_Settings_Js.editInstance = instance;
            return instance;
        }
        return CTMobileSettings_Settings_Js.editInstance;
    }
},{
    updatedBlockSequence : {},    
    registerSelectModuleChange:function() {
        jQuery("#global_search_settings").on("change","#search_module", function(e) {
            var progressIndicatorElement = jQuery.progressIndicator();
            var searchModule=jQuery(this).val();
            var selectedFields=jQuery("#global_search_settings").find("#selectedFields");
            if(searchModule !='') {
                var params= {
                    "type": "POST",
                    "url": "index.php?module=CTMobileSettings&parent=Settings&view=SettingsAjax&search_module="+searchModule,
                    "dataType":"html",
                    "data" : {}
                };
                AppConnector.request(params).then(
                    function(data) {
                        progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                        selectedFields.html(data);
                        app.changeSelectElementView(selectedFields);
                        //register all select2 Elements
                        app.showSelect2ElementView(selectedFields.find('select.select2'));
                    }
                )
            }else {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                selectedFields.html('');
            }
        });
    },
    registerSelectFieldsEvent:function() {

        jQuery('#search_module').val(jQuery('#search_module option:eq(1)').val()).trigger('change');
        jQuery('select#search_module').val(jQuery('#search_module option:eq(1)').val()).select2();

        jQuery('#global_search_settings').on("change","#moduleFields", function(e) {
            jQuery('#global_search_settings').find('input[name="active"]').attr("checked","checked");
        });
    },
    registerSaveSettings:function() {
        jQuery("#global_search_settings").on("click",".btnSaveSettings", function(e) {
            var progressIndicatorElement = jQuery.progressIndicator();
            form = jQuery(this).closest('form');
            var saveUrl = form.serializeFormData();
            AppConnector.request(saveUrl).then(
                function(data) {
                    progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                    var params = {
                        title : app.vtranslate('JS_MESSAGE'),
                        text: app.vtranslate("Field Save Successfully"),
                        animation: 'show',
                        type: 'info'
                    };
                    Vtiger_Helper_Js.showMessage(params);
                    location.reload();
                }
            );
        });
    },

    registerSortableEvent : function() {
        var thisInstance = this;
        var contents = jQuery('#arrangeModules');
        var table = contents.find('.searchModule');
        contents.sortable({
            'containment' : contents,
            'items' : table,
            'revert' : true,
            'tolerance':'pointer',
            'cursor' : 'move',
            'update' : function(e, ui) {
                thisInstance.updateBlockSequence();
            }
        });
    },
    /**
     * Function which will update module sequence
     */
    updateBlockSequence : function() {
        var thisInstance = this;
        var progressIndicatorElement = jQuery.progressIndicator({
            'position' : 'html',
            'blockInfo' : {
                'enabled' : true
            }
        });

        var sequence = JSON.stringify(thisInstance.updateBlocksListByOrder());
        progressIndicatorElement.progressIndicator({'mode' : 'hide'});
        var params = {};
        params['module'] = 'CTMobileSettings';
        params['action'] = 'ActionAjax';
        params['mode'] = 'updateSequenceNumber';
        params['sequence'] = sequence;

        AppConnector.request(params).then(
            function(data) {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
            },
            function(error) {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
            }
        );
    },
    /**
     * Function which will arrange the sequence number of modules
     */
    updateBlocksListByOrder : function() {
        var thisInstance = this;
        var contents = jQuery('#arrangeModules')
        contents.find('.searchModule').each(function(index,domElement){
            var blockTable = jQuery(domElement);

            var blockId = blockTable.data('module');
            var actualBlockSequence = blockTable.data('sequence');
            var expectedBlockSequence = (index+1);

            if(expectedBlockSequence != actualBlockSequence) {
                blockTable.data('sequence', expectedBlockSequence);
            }
            thisInstance.updatedBlockSequence[blockId] = expectedBlockSequence;
        });
        return thisInstance.updatedBlockSequence;
    },

     registerEventsForFilterChanged : function(){
        // jQuery('#module_filter').on("change", function(e) {
     jQuery('#global_search_settings').on("change","#module_filter", function(e) {
            var filterId = jQuery(this).val();
            if(filterId){
                var module =  jQuery('#search_module').val();
                var progressIndicatorElement = jQuery.progressIndicator({
                    'position' : 'html',
                    'blockInfo' : {
                        'enabled' : true
                    }
                });
                var params = {};
                params['module'] = 'CTMobileSettings';
                params['action'] = 'FilterAjax';
                params['search_module'] = module;
                params['filterId'] = filterId;

                AppConnector.request(params).then(
                function(data) {
                    progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                    jQuery('#totalRecords').find('span').html(data.result.totalRecords);
                    jQuery('#addressRecords').find('span').html(data.result.AddressRecords);
                    jQuery('#nonAddressRecords').find('span').html('<a href="#" id="nonAddressPopup">'+data.result.nonAddressRecords+'</a>');
                });
            }
         });

        jQuery('#global_search_settings').on("click","#btnsyncNow", function(e) {
            var module =  jQuery('#search_module').val();
            var filterId =  jQuery('#module_filter').val();
            var progressIndicatorElement = jQuery.progressIndicator({
                    'position' : 'html',
                    'blockInfo' : {
                        'enabled' : true
                    }
                });
                var params = {};
                params['module'] = 'CTMobileSettings';
                params['action'] = 'SyncLatLongAjax';
                params['search_module'] = module;
                params['filterId'] = filterId;

                AppConnector.request(params).then(
                function(data) {
                    progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                    var params = {
                       title : app.vtranslate("Sync GEO Location successfully"),
                       text: app.vtranslate('Sync GEO Location successfully'),
                       animation: 'show',
                       type: 'info'
                    };
                    Vtiger_Helper_Js.showPnotify(params);
                });

        });

        jQuery('#global_search_settings').on("click","#btnsyncManually", function(e) {
            location.href = "index.php?module=CTMobileSettings&parent=Settings&view=ManualSync";
        });
    },

    registerEventsForNonAddressPopup : function(){
        var popupInstance = Vtiger_Popup_Js.getInstance();
        var params = {};
         jQuery('#global_search_settings').on('click','#nonAddressPopup',function(){
            var module =  jQuery('#search_module').val();
            var filterId =  jQuery('#module_filter').val();

            params['module'] = "CTMobileSettings";
            params['view'] = "NonAddressPopup";
            params['cvid'] = filterId;
            params['src_module'] = module;
            params['page'] = 1;
           
            var popupInstance =Vtiger_Popup_Js.getInstance();
            popupInstance.show(params,function(data){
            });
        });
    },

     registerEventsForAddressPopup : function(){
        var popupInstance = Vtiger_Popup_Js.getInstance();
        var params = {};
         jQuery('#global_search_settings').on('click','#addressPopup',function(){
            var module =  jQuery('#search_module').val();
            var filterId =  jQuery('#module_filter').val();

            params['module'] = "CTMobileSettings";
            params['view'] = "AddressPopup";
            params['cvid'] = filterId;
            params['src_module'] = module;
            params['page'] = 1;
           
            var popupInstance =Vtiger_Popup_Js.getInstance();
            popupInstance.show(params,function(data){

            });
        });
    },

            /*change event of select module for auto address fields by sapna*/
    registerAutoSelectModuleChange:function() {

        table = jQuery('#example3').DataTable({
          'paging'      : true,
          'lengthChange': true,
          'searching'   : false,
          'ordering'    : false,
          'info'        : true,
          'autoWidth'   : false,
          "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'),
              },
          },
        });

        var params = {};
        params['module'] = 'CTMobileSettings';
        params['action'] = 'getListRoute';
        params['mode'] = 'getAutoAddress';
        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(); 
            }
        });

        jQuery("#global_search_settings").on("change","#autosearch_module", function(e) {
            
            var progressIndicatorElement = jQuery.progressIndicator({
              'position' : 'html',
              'blockInfo' : {
               'enabled' : true
              }
             });
            var searchModule=jQuery(this).val();
            var selectedFields=jQuery("#global_search_settings").find("#autoSelectedFields");
            if(searchModule !='') {
                var params= {
                    "type": "POST",
                    "url": "index.php?module=CTMobileSettings&parent=Settings&view=SettingsAjax&search_module="+searchModule+"&mode=autoAddressField",
                    "dataType":"html",
                    "data" : {}
                };
                AppConnector.request(params).then(
                    function(data) {
                        progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                        selectedFields.html(data);
                        app.changeSelectElementView(selectedFields);
                        //register all select2 Elements
                        app.showSelect2ElementView(selectedFields.find('select.select2'));
                    }
                )
            }else {
                progressIndicatorElement.progressIndicator({'mode' : 'hide'});
                selectedFields.html('');
            }
        });


        jQuery('#global_search_settings').on('click', '.showCTTotalCountIcon', function(e){
            var currentEle = jQuery(e.currentTarget);
            var searchModule=jQuery('#search_module').val();
            var filterid =jQuery('#module_filter').val();
            var params= {
                "type": "POST",
                'url':"index.php?module=CTMobileSettings&view=SettingsAjax&search_module="+searchModule+"&filterid="+filterid+"&mode=getTotalRecords",
                "dataType":"html",
                "data" : {}
            };
            AppConnector.request(params).then(
                function(data) {
                currentEle.text(data);
            });
        });

        jQuery('#global_search_settings').on('click', '.showCTAddressTotalCountIcon', function(e){
            var currentEle = jQuery(e.currentTarget);
            var searchModule=jQuery('#search_module').val();
            var filterid =jQuery('#module_filter').val();
            var params= {
                "type": "POST",
                'url':"index.php?module=CTMobileSettings&view=SettingsAjax&search_module="+searchModule+"&filterid="+filterid+"&mode=getTotalAddressedRecords",
                "dataType":"html",
                "data" : {}
            };
            AppConnector.request(params).then(
                function(data) {
                currentEle.text(data);
            });
        });

        jQuery('#global_search_settings').on('click', '.showCTNonAddressTotalCountIcon', function(e){
            var currentEle = jQuery(e.currentTarget);
            var searchModule=jQuery('#search_module').val();
            var filterid =jQuery('#module_filter').val();
            var params= {
                "type": "POST",
                'url':"index.php?module=CTMobileSettings&view=SettingsAjax&search_module="+searchModule+"&filterid="+filterid+"&mode=getTotalNonAddressedRecords",
                "dataType":"html",
                "data" : {}
            };
            AppConnector.request(params).then(
                function(data) {
                currentEle.text(data);
            });
        });
    },
    /* change event code end */
    
    /**
     * Function which will handle the registrations for the elements
     */
    registerEvents : function() {
        this.registerSelectModuleChange();
        this.registerAutoSelectModuleChange();
        this.registerSaveSettings();
        this.registerSelectFieldsEvent();
        this.registerSortableEvent(); 
        this.registerEventsForFilterChanged();
        this.registerEventsForNonAddressPopup();
        this.registerEventsForAddressPopup(); 
        jQuery('#geocodingReport').on('click',function(){
			var url = jQuery(this).attr('data-url');
			location.href = url;
		});      
    }
});


function deleteAutoAddressField(id) {
    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'] = 'deleteAutoSearch';
        params['id'] = id;
        var progressIndicatorElement = jQuery.progressIndicator({
            'position' : 'html',
            'blockInfo' : {
                'enabled' : true
            }
        });
        AppConnector.request(params).then(
        function(data) {
            progressIndicatorElement.progressIndicator({'mode' : 'hide'});
            if(data){
                
                var params = {};
                params['module'] = 'CTMobileSettings';
                params['action'] = 'getListRoute';
                params['mode'] = 'getAutoAddress';
                var progressIndicatorElement2 = jQuery.progressIndicator({
                    'position' : 'html',
                    'blockInfo' : {
                        'enabled' : true
                    }
                });
                AppConnector.request(params).then(
                function(data) {
                    progressIndicatorElement2.progressIndicator({'mode' : 'hide'});
                    if(data){
                        var tabledata = JSON.parse(data.result);
                        table.rows().remove();
                        table.rows.add(
                           tabledata
                        ).draw(); 
                    }
                });
                var params = {
                   title : app.vtranslate("Record deleted successfully"),
                   text: app.vtranslate('Record deleted successfully'),
                   animation: 'show',
                   type: 'info'
                };
                Vtiger_Helper_Js.showPnotify(params);
            }
        });
    });
}

function editAutoSearch(module) {
    jQuery('#autosearch_module').val(module).trigger("change");
    jQuery('#autosearch_module').select2();
}

