function Visitor() {

    "use strict";

    var self = this;

    this.initFilters = function () {
        $("#search_btn").off();
        $("#search_btn").click(function () {
            self.initSubscribersDatatable();
        });
    };

    this.initSubscribersDatatable = function () {
        $('#subscribers_datatable').DataTable({
            "aaSorting": [[ 5, 'desc' ]],
            "columnDefs": [{"orderable": false, "targets": []}],
            "lengthMenu": [[10, 25, 50, 100000000], [10, 25, 50, "All"]],
            "searchDelay": 2000,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "type": "GET",
                "url": application.url+'/admin/subscribers/data',
                "data": function ( d ) {
                    // d.visit_unit = $('#visit_unit').val();
                },
                "complete": function (response) {
                    self.initViewVisitor();
                    self.initiCheck();
                    self.initAllCheck();
                    $('.table-bordered').parent().attr('style', 'overflow:auto'); //For responsive
                },
            },
            'paging': true,
            'lengthChange': true,
            'searching': true,
            'info': true,
            'autoWidth': true,
            'destroy':true,
            'stateSave': true,
            'responsive': true
        });
    };

    this.initEntryFilters = function () {
        $("#search_bt").off();
        $("#search_bt").click(function () {
            self.initVisitorEntryDatatable();
        });
    };

    this.initVisitorEntryDatatable = function () {
        $('#visitorentry_datatable').DataTable({
            "aaSorting": [[ 4, 'desc' ]],
            "columnDefs": [{"orderable": false, "targets": [0,1,2]}],
            "lengthMenu": [[10, 25, 50, 100000000], [10, 25, 50, "All"]],
            "searchDelay": 2000,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "type": "GET",
                "url": application.url+'/admin/subscribers/entrydata',
                "data": function ( d ) {
                    d.visit_unit = $('#visit_unit').val();
                },
                "complete": function (response) {
                    self.initViewVisitor();
                    self.initiCheck();
                    self.initAllCheck();
                    $('.table-bordered').parent().attr('style', 'overflow:auto'); //For responsive
                },
            },
            'paging': true,
            'lengthChange': true,
            'searching': true,
            'info': true,
            'autoWidth': true,
            'destroy':true,
            'stateSave': true,
            'responsive': true
        });
    };

    this.initSubscribersSave = function () {
        application.onSubmit('#admin_visitor_create_update_form', function (result) {
            application.showLoader('admin_visitor_create_update_form_button');
            application.post('admin/subscribers/save', '#admin_visitor_create_update_form', function (res) {
                var result = JSON.parse(application.response);
                if (result.success === 'true') {
                    console.log("Saved");
                    location.href=application.url+'admin/subscribers';
                } else {
                    application.hideLoader('admin_visitor_create_update_form_button');
                    application.showMessages(result.messages, 'admin_visitor_create_update_form');
                }
            });
        });
    };

    this.initiCheck = function () {
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
          checkboxClass: 'icheckbox_minimal-blue',
          radioClass   : 'iradio_minimal-blue'
        });
    };

    this.initAllCheck = function () {
        $('input.all-check').on('ifChecked', function(event){
            $('input.single-check').iCheck('check');
        });
        $('input.all-check').on('ifUnchecked', function(event){
            $('input.single-check').iCheck('uncheck');
        });
    };

    this.initViewVisitor = function () {
        $('.visitor-entry').off();
        $('.visitor-entry').on('click', function () {
            var button = $(this);
            var id = $(this).data('id');
            var modal = '#modal-default';
            var modal_title = 'Visitor Entry';
            $(modal).modal('show');
            $(modal+' .modal-title').html(modal_title);
            application.load('admin/subscribers/entry/'+id, modal+' .modal-body-container', function (result) {
                self.initSaveEntry();
            });
        });
    }

    this.initFlatChange = function () {
        console.log("coming initFlatChange")
        $("#flat_id").change(function () {
            var id = $("#flat_id").val();
            if(id != '')
            {
                $.ajax({
                    url : application.url+'admin/subscribers/getFlatOwner/'+id,
                    method : "GET",
                    async : true,
                    dataType : 'json',
                    success: function(data){
                        console.log(data)
                        $('#flat_owner').val(data.username);
                    }
                });
                return false;
            } else {
                $('#flat_owner').html();
            }
        });
    }

    this.initSaveEntry = function() {
        application.onSubmit('#admin_ventry_create_update_form', function (result) {
            application.showLoader('admin_ventry_create_update_form_button');
            application.post('admin/subscribers/saveEntry', '#admin_ventry_create_update_form', function (res) {
                var result = JSON.parse(application.response);
                if (result.success === 'true') {
                    console.log("Saved");
                    location.href=application.url+'admin/subscribers/entry';
                } else {
                    application.hideLoader('admin_ventry_create_update_form_button');
                    application.showMessages(result.messages, 'admin_ventry_create_update_form');
                }
            });
        });
    }

    this.initChangeTime = function () {
        $('.change-time').off();
        $('.change-time').on('click', function () {
            var visitor_id = $("#visitor_id").val();
            var in_person = $("#in_person").val();
            application.load('admin/subscribers/changetime/'+visitor_id+'/'+in_person, '', function (result) { 
                var result = JSON.parse(application.response);
                if(result.success == 'true')
                {
                    $("#show_visitor_single").html('Current Time set as IN-TIME for this visitor.');         
                    $("#show_visitor").show();
                    setTimeout(function() { $("#show_visitor").hide(); }, 5000);
                }
            });
        });
    };

    this.downloadVisitorExcel = function (ids) {
        var form = "#subscribers-form";
        $("<input />").attr("type", "hidden").attr("name", "ids").attr("value", ids).appendTo(form);
        $("<input />").attr("type", "hidden").attr("name", "csrf_token").attr("value", application.csrf_token).appendTo(form);
        $(form).submit();
    };

    this.initSubscribersListBulkActions = function () {
        console.log("initSubscribersListBulkActions")
        $('.visitor-bulk-action').off();
        $('.visitor-bulk-action').on('click', function (e) {
            console.log("Button Clicked")
            e.preventDefault();
            var ids = [];
            var action = $(this).data('action');
            $('.single-check').each(function (i, v) {
                if ($(this).is(':checked')) {
                    ids.push($(this).data('id'))
                }
            });
            console.log(ids)
            if (ids.length === 0) {
                alert(lang['please_select_some_records_first']);
                $('.visitor-bulk-action').val('');
                return false;
            }
            console.log(action)
            if (action == 'download-excel-visitor') {
                self.downloadVisitorExcel(ids);
            }
        });
    };

    this.downloadVisitEntryExcel = function (ids) {
        var form = "#visitentry-form";
        $("<input />").attr("type", "hidden").attr("name", "ids").attr("value", ids).appendTo(form);
        $("<input />").attr("type", "hidden").attr("name", "csrf_token").attr("value", application.csrf_token).appendTo(form);
        $(form).submit();
    };

    this.initVisitEntryListBulkActions = function () {
        $('.bulk-action').off();
        $('.bulk-action').on('click', function (e) {
            e.preventDefault();
            var ids = [];
            var action = $(this).data('action');
            $('.single-check').each(function (i, v) {
                if ($(this).is(':checked')) {
                    ids.push($(this).data('id'))
                }
            });
            if (ids.length === 0) {
                alert(lang['please_select_some_records_first']);
                $('.bulk-action').val('');
                return false;
            }
            if (action == 'download-visitentry-excel') {
                self.downloadVisitEntryExcel(ids);
            }
        });
    };

}

$(document).ready(function() {
    var visitor = new Visitor();
    visitor.initFilters();
    visitor.initSubscribersDatatable();
    visitor.initChangeTime();
    visitor.initSubscribersSave();
    visitor.initEntryFilters();
    visitor.initVisitorEntryDatatable();
    visitor.initFlatChange();
    visitor.initSubscribersListBulkActions();
    visitor.initVisitEntryListBulkActions();

    $("#visiting_date").datetimepicker({
        minDate:new Date(),
        disabledDates: [new Date()],
        format: 'yyyy-mm-dd hh:ii'
    });



// Barcode Search 
    document.addEventListener("keypress", function(e) {
      if (e.target.tagName !== "INPUT") {
        var input = document.querySelector("#fbarcode_string");
        input.focus();
        input.value = e.key;
        e.preventDefault();
      }
    });




});

function searchFilter () {
    $.ajax({
            url : application.url+'admin/vfilterajax',
            type : "GET",
            data : {
                'mobile' : $('#fmobile').val(),
                'nric' : $('#fnric').val(),
                'barcode_string' : $('#fbarcode_string').val()
            },
            beforeSend: function () {
                $('.loading').show();
            },
            success : function(data) {
                // do something
                $('#subscribers_ajax_search').html(data);
                $('.loading').fadeOut("slow");
            },
            error : function(data) {
                // do something
                console.log("Error")
            }
        });
}
