/* ------------------------------------------------------------------------------

*

*  # JS for post page

*

*  Specific JS code additions for ./post page

*

*  Version: 1.0

*  Latest update: April, 14 2016

*

* ---------------------------------------------------------------------------- */

$(function() {



    $.fn.modal.Constructor.prototype.enforceFocus = function() {};



    var base_url       = $('#base-url').val(),

        module         = 'pesertadidik';



    if ($.isFunction($.fn.dataTable) && $('#pesertadidik-list-ajax').length > 0)

    {

      // Table setup

      // ------------------------------



      // /datatables

      tabelPesertadidik = $('#pesertadidik-list-ajax').DataTable({

          "processing": true, //Feature control the processing indicator.

          "serverSide": true, //Feature control DataTables' server-side processing mode.

          "order": [6 , 'desc'], //Initial no order.

          "autoWidth": false,



          // Load data for the table's content from an Ajax source

          "ajax": {

              "url": base_url + module +"/pesertadidik_ajax",

              "type": "POST",

              "data": function(d){

                return $.extend({}, d, {

                     "jenis_kelamin" :$("#filter-jenis-kelamin option:selected").val(),

                     "alat_transportasi_id" :$("input[name=alat_transportasi_id]").val(),

                     "asrama_id" :$("input[name=prasarana_id]").val()

                })

            }

          },



          //Set column definition initialisation properties.

          "columnDefs": [

            {

                "targets": [0,4], //first column / numbering column

                "orderable": false, //set not orderable



            },

            {

                orderable: false,

                width: '300px',

                className : 'text-center',

                targets: [ 6 ]

            }

          ],

          dom: '<"datatable-header"fl><"datatable-scroll"t>r<"datatable-footer"ip>',

          language: {

              processing : '<i class="icon-spinner2 spinner position-left"></i> Silahkan Tunggu  ',

              search: '<span>Filter:</span> _INPUT_',

              searchPlaceholder: 'Ketik untuk mencari nama ...',

              lengthMenu: '<span>Tampilkan:</span> _MENU_',

              paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }

          },

          drawCallback: function () {

              $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');



              $(".styled").uniform({

                  radioClass: 'choice'

              });

          },

          preDrawCallback: function() {

              $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');

          }

      });



      // External table additions

      // ------------------------------



      // Add select bulk action option

      $select   = '<div id="filter-jenis-kelamin" class="dataTables_length pull-left">\
                    <label><span>Jenis Kelamin:</span>\
                       <select name="jenis-kelamin" class="select2" data-width="200px">\
                         <option value="">-- Semua --</option>\
                         <option value="L">Laki-laki</option>\
                         <option value="P">Perempuan</option>\
                       </select>\
                      </label>\
                    </div>';



      $(".datatable-header").prepend($select);



      // Enable Select2 select for the length option

      $('.dataTables_length select').select2({

          minimumResultsForSearch: Infinity,

          width: 'auto'

      });



      $(document).on('change','#filter-jenis-kelamin select', function(e){

        tabelPesertadidik.ajax.reload();

      });



      if($('[name=alat_transportasi_id]').length > 0)

      {

        // Get the column API object

        var column = tabelPesertadidik.column(6);



        // Toggle the visibility

        column.visible(false);

      }



    }



    if ($.isFunction($.fn.dataTable) && $('#pdb-list-ajax').length > 0)

    {

      // Table setup

      // ------------------------------



      // /datatables

      pdb = $('#pdb-list-ajax').DataTable({

          "processing": true, //Feature control the processing indicator.

          "serverSide": true, //Feature control DataTables' server-side processing mode.

          "order": [7 , 'desc'], //Initial no order.

          "autoWidth": false,



          // Load data for the table's content from an Ajax source

          "ajax": {

              "url": base_url + "pesertadidik/pdb_ajax",

              "type": "POST",

              "data": function(d){

                return $.extend({}, d, {

                     "jenis_kelamin" :$("#filter-jenis-kelamin option:selected").val(),

                     "bentuk_pendidikan_id" :$("#filter-bentuk-pendidikan option:selected").val(),

                     "tahun_ajaran_id" :$("#filter-tahun-ajaran option:selected").val()

                })

            }

          },



          //Set column definition initialisation properties.

          "columnDefs": [

            {

                "targets": [0,4], //first column / numbering column

                "orderable": false, //set not orderable



            },

            {

                orderable: false,

                width: '300px',

                className : 'text-center',

                targets: [ 6 ]

            }

          ],

          dom: '<"datatable-header"fl><"datatable-scroll"t>r<"datatable-footer"ip>',

          language: {

              processing : '<i class="icon-spinner2 spinner position-left"></i> Silahkan Tunggu  ',

              search: '<span>Filter:</span> _INPUT_',

              searchPlaceholder: 'Ketik untuk mencari nama ...',

              lengthMenu: '<span>Tampilkan:</span> _MENU_',

              paginate: { 'first': 'First', 'last': 'Last', 'next': '&rarr;', 'previous': '&larr;' }

          },

          drawCallback: function () {

              $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').addClass('dropup');



              $(".styled").uniform({

                  radioClass: 'choice'

              });

          },

          preDrawCallback: function() {

              $(this).find('tbody tr').slice(-3).find('.dropdown, .btn-group').removeClass('dropup');

          }

      });



      // External table additions

      // ------------------------------



      // Add select bulk action option

        $select   = '<div id="filter-jenis-kelamin" class="dataTables_length pull-left">\
                    <label><span>Jenis Kelamin:</span>\
                       <select name="jenis-kelamin" class="select2" data-width="120px">\
                         <option value="">-- Semua --</option>\
                         <option value="L">Laki-laki</option>\
                         <option value="P">Perempuan</option>\
                       </select>\
                      </label>\
                    </div>';



        $select   += '<div id="filter-bentuk-pendidikan" class="dataTables_length pull-left">\
                    <label><span>Unit:</span>\
                       <select name="bentuk_pendidikan_id" class="select2-search" data-width="120px">\
                         <option value="">-- Semua --</option>\
                         <option value="12">SMA</option>\
                         <option value="6">SMP</option>\
                         <option value="5">SD</option>\
                         <option value="1">TK/KB</option>\
                       </select>\
                      </label>\
                    </div>';



        $select   += '<div id="filter-tahun-ajaran" class="dataTables_length pull-left">\
                    <label><span>Tahun Ajaran:</span>\
                       <select name="tahun_ajaran_id" data-filter="periode_aktif-1" class="select2-master" data-master="tahun_ajaran" data-width="120px">\
                         <option value="">-- Semua --</option>\
                       </select>\
                      </label>\
                    </div>';



      $(".datatable-header").prepend($select);



      // Enable Select2 select for the length option

      $('.dataTables_length select').select2({

          minimumResultsForSearch: Infinity,

          width: 'auto'

      });



      $(document).on('change','#filter-jenis-kelamin select, #filter-bentuk-pendidikan select, #filter-tahun-ajaran select ', function(e){

        pdb.ajax.reload();

      });



    }



    if ($.isFunction($.fn.validate )) {



    // Setup validation

    // ------------------------------



    // Initialize

    var validator = $(".form-validate-jquery").validate({

        ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields

        errorClass: 'validation-error-label',

        successClass: 'validation-valid-label',

        highlight: function(element, errorClass) {

            $(element).removeClass(errorClass);

        },

        unhighlight: function(element, errorClass) {

            $(element).removeClass(errorClass);

        },



        // Different components require proper error label placement

        errorPlacement: function(error, element) {



            // Styled checkboxes, radios, bootstrap switch

            if (element.parents('div').hasClass("checker") || element.parents('div').hasClass("choice") || element.parent().hasClass('bootstrap-switch-container') ) {

                if(element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {

                    error.appendTo( element.parent().parent().parent().parent() );

                }

                 else {

                    error.appendTo( element.parent().parent().parent().parent().parent() );

                }

            }



            // Unstyled checkboxes, radios

            else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {

                error.appendTo( element.parent().parent().parent() );

            }



            // Input with icons and Select2

            else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {

                error.appendTo( element.parent() );

            }



            // Inline checkboxes, radios

            else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {

                error.appendTo( element.parent().parent() );

            }



            // Input group, styled file input

            else if (element.parent().hasClass('uploader') || element.parents().hasClass('input-group')) {

                error.appendTo( element.parent().parent() );

            }



            else {

                error.insertAfter(element);

            }

        },

        validClass: "validation-valid-label",

        rules: {},

        messages: {}

    });



    }



    if ($('.select2-master').length > 0)

    {

        $('.select2-master').each(function(e) {

            let elm     = $(this),

                options = {

                    allowClear: true,

                    delay: 250,

                    width: '120px',

                    ajax: {

                        url: base_url +"/master/mst_ajax",

                        dataType: 'json',

                        data: function(params){

                            return $.extend({}, params, {

                                term: params.term || '',

                                page: params.page || 1,

                                master : elm.data('master'),

                                filter : elm.attr('data-filter')

                            })

                          },

                        cache: true

                    }

                };



                $(elm).select2(options);



        });

    }



    if ($('form').length > 0)

    {

        $('input[name="penerima_kps"]').on('change', function() {

            let noKps = $('input[name="no_kps"]');

            noKps.prop('disabled', !noKps.prop('disabled'));

        });



        $('input[name="jarak_rumah_ke_sekolah"]').on('change', function() {

            let jarak = $('input[name="jarak_rumah_ke_sekolah_km"]');

            jarak.prop('disabled', !jarak.prop('disabled'));

        });



        $('input[name="penerima_kip"]').on('change', function() {

            let noKps = $('input[name="no_kip"]');

            let nmKps = $('input[name="nm_kip"]');



            noKps.prop('disabled', !noKps.prop('disabled'));

            nmKps.prop('disabled', !nmKps.prop('disabled'));

        });



        $('input[name="layak_pip"]').on('change', function() {

            let id_layak_pip = $('select[name="id_layak_pip"]');

            id_layak_pip.prop('disabled', !id_layak_pip.prop('disabled'));

        });

    }



    $('#modal_form_orangtua form').on('submit', function(e) {

        e.preventDefault();

        let elm = $(this);

        let data = elm.serializeArray();



        $.ajax({

            url : base_url + '/pesertadidik/add_orangtua',

            method : 'POST',

            dataType : 'JSON',

            data : data

        }).done(function(result) {

            $('.close-form-orangtua').click();

            console.log(result);

            $.jGrowl(result.message , {

                theme: 'bg-success'

            });



        }).fail(function(err) {

            $.jGrowl(err , {

                theme: 'bg-danger'

            });

        });





    });



    $(document).on('click','.generate-account', function(e) {

        e.preventDefault();

        data = $(this).data('account');

        console.log(data);

        $.ajax({

            method : 'POST',

            url : base_url + 'auth/create_user_ajax',

            dataType : 'JSON',

            data : data

        }).done(function(result) {

            console.log(result);

            $.jGrowl(result.message , {

                theme: 'bg-success',

                life: 10000

            });

            tabelPesertadidik.ajax.reload();

        }).fail(function(err) {

            console.log(err);

            $.jGrowl(err , {

                theme: 'bg-danger',

                life: 5000

            });

        });

    })



});

