function Job() {

    "use strict";

    var self = this;

    this.initFilters = function () {
        $("#status, #company").off();
        $("#status, #company").change(function () {
            self.initJobsDatatable();
        });
        $('.select2').select2();
    };
    
    this.initAppliedFilters = function () {
        $("#jobs, #users").off();
        $("#jobs, #users").change(function () {
            self.initAppliedJobsDatatable();
        });
        $('.select2').select2();
    };

    this.initJobsDatatable = function () {
        $('#jobs_datatable').DataTable({
            "aaSorting": [[ 5, 'desc' ]],
            "columnDefs": [{"orderable": false, "targets": [0,7]}],
            "lengthMenu": [[10, 25, 50, 100000000], [10, 25, 50, "All"]],
            "searchDelay": 2000,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "type": "GET",
                "url": application.url+'admin/jobs/data',
                "data": function ( d ) {
                    d.status = $('#status').val();
                    d.company = $('#company').val();
                },
                "complete": function (response) {
                    self.initiCheck();
                    self.initAllCheck();
                    self.initJobCreateOrEditForm();
                    self.initJobChangeStatus();
                    self.initJobDelete();
                    $('.table-bordered').parent().attr('style', 'overflow:auto'); //For responsive
                },
            },
            'paging': true,
            'lengthChange': true,
            'searching': true,
            'info': true,
            'autoWidth': true,
            'destroy':true,
            'stateSave': true
        });
    };
    
    this.initAppliedJobsDatatable = function () {
        $('#appliedjobs_datatable').DataTable({
            "aaSorting": [[ 10, 'desc' ]],
            "columnDefs": [{"orderable": false, "targets": [0,3,4,6,7,11]}],
            "lengthMenu": [[10, 25, 50, 100000000], [10, 25, 50, "All"]],
            "searchDelay": 2000,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "type": "GET",
                "url": application.url+'admin/appliedjobs/data',
                "data": function ( d ) {
                    d.job = $('#jobs').val();
                    d.user = $('#users').val();
                },
                "complete": function (response) {
                    self.initiCheck();
                    self.initAllCheck();
                    self.initCandidateDelete();
                    $('.table-bordered').parent().attr('style', 'overflow:auto'); //For responsive
                },
            },
            'paging': true,
            'lengthChange': true,
            'searching': true,
            'info': true,
            'autoWidth': true,
            'destroy':true,
            'stateSave': true
        });
    };

    this.initJobSave = function () {
        application.onSubmit('#admin_job_create_update_form', function (result) {
            for(var instanceName in CKEDITOR.instances)
                CKEDITOR.instances[instanceName].updateElement();
            application.showLoader('admin_job_create_update_form_button');
            application.post('admin/jobs/save', '#admin_job_create_update_form', function (res) {
                var result = JSON.parse(application.response);
                application.hideLoader('admin_job_create_update_form_button');
//                if(result.success == 'true' && !result.state)
//                {     
//                    location.href="admin/jobs/create-or-edit/"+result.state;
//                    $('#admin_job_create_update_form').trigger("reset");
//                    for(var instanceName in CKEDITOR.instances)
//                        CKEDITOR.instances[instanceName].setData('');
//                }
                  if(result.success == 'false' && result.state == '')
                    application.showMessages(result.messages, 'admin_job_create_update_form');
                  else
                    window.location.href = application.url+"admin/jobs/create-or-edit/"+result.id+"/"+result.state;
            });
        });
    };

    this.initJobCreateOrEditForm = function () {
        $('.create-or-edit-job').off();
        $('.create-or-edit-job').on('click', function () {
            var id = $(this).data('id');
            id = id ? '/'+id : '';
            if(id)
            {
                window.location = application.url+'admin/jobs/create-or-edit'+id+'/'+null;          
            } else {
                window.location = application.url+'admin/jobs/create-or-edit';
            }
        });
    };

    this.initJobChangeStatus = function () {
        $('.change-job-status').off();
        $('.change-job-status').on('click', function () {
            var button = $(this);
            var id = $(this).data('id');
            var status = parseInt($(this).data('status'));
            button.html("<i class='fa fa-spin fa-spinner'></i>");
            button.attr("disabled", true);
            application.load('admin/jobs/status/'+id+'/'+status, '', function (result) {
                button.removeClass('btn-success');
                button.removeClass('btn-danger');
                button.addClass(status === 1 ? 'btn-danger' : 'btn-success');
                button.html(status === 1 ? lang['inactive'] : lang['active']);
                button.data('status', status === 1 ? 0 : 1);
                button.attr("disabled", false);
                button.attr("title", status === 1 ? lang['click_to_activate'] : lang['click_to_deactivate']);
            });
        });
    };

    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.initJobDelete = function () {
        $('.delete-job').off();
        $('.delete-job').on('click', function () {
            var status = confirm(lang['are_u_sure']);
            var id = $(this).data('id');
            if (status === true) {
                application.load('admin/jobs/delete/'+id, '', function (result) {
                    self.initJobsDatatable();
                });
            }
        });
    };
    
    this.initCandidateDelete = function () {
        $('.delete-candidate').off();
        $('.delete-candidate').on('click', function () {
            var status = confirm(lang['are_u_sure']);
            var id = $(this).data('id');
            if (status === true) {
                application.load('admin/candidates/delete/'+id, '', function (result) {
                    self.initAppliedJobsDatatable();
                });
            }
        });
    };

    this.initJobsListBulkActions = function () {
        $('.bulk-action').off();
        $('.bulk-action').on('click', function () {
            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;
            } else if (action == 'download-excel') {
                var form = "#jobs-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();
            } else if (action == 'download-excelApplied') {
                var form = "#candidates-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();
            } else if (action == 'resend') {
                application.post('admin/jobs/resend-form', {ids:ids, action: $(this).data('action')}, function (result) {
                    $('.bulk-action').val('');
                    $('.all-check').prop('checked', false);
                    var result = JSON.parse(application.response);
                    $("#show_msg").html(result.messages);                
                    $("#show_msg").show();
                    setTimeout(function() { $("#show_msg").hide(); }, 5000);
                    self.initAppliedJobsDatatable();
                });
            } else {
                application.post('admin/jobs/bulk-action', {ids:ids, action: $(this).data('action')}, function (result) {
                    $('.bulk-action').val('');
                    $('.all-check').prop('checked', false);
                    self.initJobsDatatable();
                });
            }
        });
    };

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

    this.initRemoveCustomField = function () {
        $('.remove-custom-field').off();
        $('.remove-custom-field').on('click', function () {
            var button = $(this);
            var id = $(this).data('id');
            var status = confirm(lang['are_u_sure']);
            if (status === true) {
                if (id != '') {
                    application.load('admin/jobs/remove-custom-field/'+id, '', function (result) {
                        button.parent().parent().parent().parent().remove();
                    });
                } else {
                    button.parent().parent().parent().parent().remove();
                }
                self.initShowHideEmptyCustomField();
            }
        });
    }

    this.initAddCustomField = function () {
        $('.add-custom-field').off();
        $('.add-custom-field').on('click', function (event) {
            event.preventDefault();
            application.load('admin/jobs/add-custom-field', '', function (result) {
                $('.custom-fields-container').append(application.response);
                self.initRemoveCustomField();
                self.initShowHideEmptyCustomField();
            });
        });
    };

    this.initShowHideEmptyCustomField = function () {
        if ($('.custom-value-box').length == 0) {
            $('.no-custom-value-box').show();
        } else {
            $('.no-custom-value-box').hide();
        }
    };    

    this.initCKEditor1 = function () {
        var elementExists = document.getElementById("description");
        if (elementExists) {
            CKEDITOR.replace('description', {
                allowedContent : true,
                filebrowserUploadUrl: application.url+'/admin/ckeditor/images/upload?CKEditorFuncNum=1',
                filebrowserUploadMethod: 'form',
            });
        }
    };
    
    this.initCKEditor2 = function () {
        var elementExists = document.getElementById("key_responsibilities");
        if (elementExists) {
            CKEDITOR.replace('key_responsibilities', {
                allowedContent : true,
                filebrowserUploadUrl: application.url+'/admin/ckeditor/images/upload?CKEditorFuncNum=1',
                filebrowserUploadMethod: 'form',
            });
        }
    };
    
    this.initCKEditor3 = function () {
        var elementExists = document.getElementById("knowledge_text");
        if (elementExists) {
            CKEDITOR.replace('knowledge_text', {
                allowedContent : true,
                filebrowserUploadUrl: application.url+'/admin/ckeditor/images/upload?CKEditorFuncNum=1',
                filebrowserUploadMethod: 'form',
            });
        }
    };
    
    this.printPage = function () {
        $('.btnPrintWebPage').off();
        $('.btnPrintWebPage').on('click', function () {
            var ht = $(window).height();
            var wt = $(window).width();
            var divContents = $(".content-wrapper").html();
            var printWindow = window.open('', '', 'height=' + ht + 'px,width=' + wt + 'px');
            printWindow.document.write('<html><head><title>Rail Bhojan Order details</title>');
            printWindow.document.write('<link href="<?=base_url()?>web_assets/css/bootstrap.css" rel="stylesheet" media="screen">  <link href="<?=base_url()?>web_assets/css/custom.css" rel="stylesheet" media="screen">');
            printWindow.document.write('</head><body>');
            printWindow.document.write(divContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        });
    };
    
}

$(document).ready(function() {
    var job = new Job();

    //For both screens
    job.initiCheck();

    //For listing screen
    job.initFilters();
    job.initAppliedFilters();
    job.initJobsDatatable();
    job.initAppliedJobsDatatable();
    job.initJobsListBulkActions();
    
    //For create edit screen
    job.initJobSave();
    job.initAddCustomField();
    job.initRemoveCustomField();
    job.initShowHideEmptyCustomField();
    job.initCKEditor1();
    job.initCKEditor2();
    job.initCKEditor3();
    job.printPage();

    var company = new Company(); //From company.js
    company.initCompanyCreateOrEditForm();
    
});

function print(obj)
{
    var url = obj.value;   
    var printWindow = window.open( url, 'Print', 'left=200, top=200, width=950, height=500, toolbar=0, resizable=0');

    printWindow.addEventListener('load', function() {
        if (Boolean(printWindow.chrome)) {
            printWindow.print();
            setTimeout(function(){
                printWindow.close();
            }, 100);
        } else {
            printWindow.print();
            printWindow.close();
        }
    }, true);
}


