/* loader */
$(window).on('load', function(){
	$('#loader').transition('fade');
})

/* slug */
function stringToSlug(str) {
    str = str.toString().replace(/^\s+|\s+$/g, ''); // trim
    str = str.toLowerCase();

    str = str.toString().replace(/[^a-z0-9 -]/g, '') // remove invalid chars
        .toString().replace(/\s+/g, '-') // collapse whitespace and replace by -
        .toString().replace(/-+/g, '-'); // collapse dashes

    return str;
}

$(function(){
    /* menu sidebar toggle */
    /* mobile display */
    $(document).on('click', '.module-left-bars', function(){
        var vis = $('.module-left-container').hasClass("visible"); 
        $('.module-left-container').transition('slide right');
        
        if(vis == false){
            $('.module-content-container').addClass('mobile-ver');
            $(this).empty().append('<i class="ti-close"></i>');
            $('.module-content-container').css("position", "fixed");
        }else{
            $('.module-content-container').removeClass('mobile-ver');
            $(this).empty().append('<i class="ti-menu"></i>');
            $('.module-content-container').css("position", "relative");
        }
    });
    $(document).on('click', '.mobile-ver', function(){
        $(this).removeClass('mobile-ver');
        $('.module-left-container').transition('slide right');
        $('.module-left-bars').empty().append('<i class="ti-menu"></i>');
        $('.module-content-container').css("position", "relative");
    });
    $(document).on('click', '.module-bar-patient-open', function(){
        alert('sdjasjdljs');
        var vis = $('.module-content-left').hasClass("visible"); 
        $('.module-content-left').transition('slide right');
        
        if(vis == false){
            $('.container-left').addClass('pt-mobile-ver');
            $('.module-bar-patient-open').empty().append('<i class="ti-close"></i>');
            $('.container-left').css("position", "fixed");
        }else{
            $('.container-left').removeClass('pt-mobile-ver');
            $('.module-bar-patient-open').empty().append('<i class="ti-menu"></i>');
            $('.container-left').css("position", "relative");
        }
    });
    $(document).on('click', '.pt-mobile-ver', function(){
        $(this).removeClass('mobile-ver');
        $('.module-content-left').transition('slide right');
        $('.module-bar-patient-open').empty().append('<i class="ti-menu"></i>');
        $('.container-left').css("position", "relative");
    });


    /* metismenu */
    $('#module-left-menu').metisMenu();

    /* slimscroll */
    $('.module-left-nav').slimScroll({
        height: '100%',
        size: '5px'
    });
    $('.module-left-list').slimScroll({
        height: '100%',
        size: '5px'
    });

    /* semantic */
    $('.ui.accordion').accordion();
    $('.ui.dropdown').dropdown();
    $('.ui.radio.checkbox').checkbox();
    $('.ui.checkbox').checkbox();
    $('.special.card .image').dimmer({
        on: 'hover'
    });

    /* toastr */
    toastr.options = {
        "positionClass": "toast-bottom-right"
    }

    /* redactor */
    $('#redactor-slider').redactor({
        /*air: true,*/
        focus: true,
        buttons: ['format', 'bold', 'italic', 'lists', 'horizontalrule'],
        plugins: ['source'],
        imageUpload: base_url+'apiRedactorUpload',
        imageResizable: true,
        imagePosition: true
    });
    $('.redactor-air').redactor({
        air: true,
        buttons: ['format', 'bold', 'italic', 'lists', 'horizontalrule'],
        imageUpload: base_url+'apiRedactorUpload',
        imageResizable: true,
        imagePosition: true
    });
    $('.redactor').redactor({
        /*air: true,*/
        plugins: ['table', 'source'],
        imageUpload: base_url+'apiRedactorUpload',
        imageResizable: true,
        imagePosition: true
    });
});

$(document).ready(function(){
    /* datatable */
    $('#example').DataTable({
        'dom':'<"top"f>rt<"bottom"<"col-md-6"i><"col-md-6 right"p>><"clear">',
        'language': {
            'zeroRecords': 'Maaf, Data tidak ditemukan',
            'infoEmpty' : 'Tidak ada record data',
            'info' : 'Halaman _PAGE_ dari _PAGES_. Total records: _TOTAL_',
            'search': '<form class="ui form"><div class="field"><div class="ui left icon input"><i class="search icon"></i> _INPUT_ </div></div></form>',
            'searchPlaceholder': 'Search...',
            'paginate':{
                'previous': '&laquo',
                'next': '&raquo'

            },
            'infoFiltered': '<br/>(dari _MAX_ total record)',
            'responsive': true,
            'columnDefs': [
                { 'responsivePriority': 1, 'targets': 0 },
                { 'responsivePriority': 2, 'targets': -1 }
            ]
        }
    });


    /* upload image */
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#img').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    function readSingleURL(input, cimg) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#'+cimg).attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }

    function uploadGallery(input){
        console.log(input.files);
        if(input.files){
            var count = input.files.length;
            var data = new FormData();
            

            for(var i=0; i<count; i++){
                var reader = new FileReader();
                reader.onload = function(e){
                    //$($.parseHTML('<img>')).attr('src', event.target.result).appendTo('#multiimg');
                    //$('#img'+i).attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[i]);
                console.log(input.files[i]);
                data.append('userfiles[]', input.files[i]);
            }



            $.ajax({
                url: base_url+'apiUploadImageGallery',
                type: 'POST',
                data: data,
                cache: false,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    
                    if(response){
                        $.each(response, function(i, item){
                            //$($.parseHTML('<img>')).attr('src', base_url+'assets/images/_temp/'+item).appendTo('#multiimg');
                            //$('<img>').attr('src', base_url+'assets/images/_temp/'+item).appendTo('#multiimg');
                            var fileupl = item.split('.');
                            var fitem = fileupl[1];

                            if(fitem == 'jpg' || fitem == 'jpeg' || fitem == 'png' || fitem == 'gif' || fitem == 'JPG' || fitem == 'JPEG'){
                                $('#multiimg').append('<div class="img-item" data-image="'+item+'">'+
                                    '<a href="#"><img src="'+base_url+'assets/images/_gallery/'+item+'"></a>'+
                                    '<div class="img-link">'+
                                        //'<a href="#" class="edit edit-caption-image" data-id="0" data-image="'+item+'" title="Edit Caption"><i class="ti-pencil-alt"></i></a>'+
                                        '<a href="#del" class="delete delete-image" data-id="0" data-image="'+item+'" title="Delete"><i class="ti-close"></i></a>'+
                                    '</div>'+
                                    '</div>');
                            }else{
                                $('#multiimg').append('<div class="img-item" data-image="'+item+'">'+
                                    '<a href="#"><video controls preload="metadata"><source src="'+base_url+'assets/images/_gallery/'+item+'#t=0.9">Your browser does not support HTML5 video.</video></a>'+
                                    '<div class="img-link">'+
                                        //'<a href="#" class="edit edit-caption-image" data-id="0" data-image="'+item+'" title="Edit Caption"><i class="ti-pencil-alt"></i></a>'+
                                        '<a href="#del" class="delete delete-image" data-id="0" data-image="'+item+'" title="Delete"><i class="ti-close"></i></a>'+
                                    '</div>'+
                                    '</div>');
                            }
                            

                            $('#multiupload').append('<input type="hidden" class="filename" name="filename[]" data-id="'+item+'" value="'+item+'">'+
                                '<input type="hidden" class="caption" name="caption[]" data-id="'+item+'" placeholder="Keterangan Gambar" maxlength="100">');
                        });
                    }
                    //$('#msg').html(response); // display success response from the PHP script
                },
                error: function (response) {
                    console.log(response);
                    //$('#msg').html(response); // display error response from the PHP script
                }
            });
        }
    }

    function readMultiURL(input){
        if(input.files){
            var count = input.files.length;
            var data = new FormData();
            

            for(var i=0; i<count; i++){
                var reader = new FileReader();
                reader.onload = function(e){
                    //$($.parseHTML('<img>')).attr('src', event.target.result).appendTo('#multiimg');
                    //$('#img'+i).attr('src', e.target.result);
                }
                reader.readAsDataURL(input.files[i]);

                data.append('userfiles[]', input.files[i]);
            }

            $.ajax({
                url: base_url+'apiUploadImageRoom',
                type: 'POST',
                data: data,
                cache: false,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    /*console.log(response);*/
                    if(response){
                        $.each(response, function(i, item){
                            //$($.parseHTML('<img>')).attr('src', base_url+'assets/images/_temp/'+item).appendTo('#multiimg');
                            //$('<img>').attr('src', base_url+'assets/images/_temp/'+item).appendTo('#multiimg');
                            $('#multiimg').append('<div class="img-item" data-image="'+item+'">'+
                                '<a href="#"><img src="'+base_url+'assets/images/_temp/'+item+'"></a>'+
                                '<div class="img-link">'+
                                    //'<a href="#" class="edit" title="Edit Caption"><i class="ti-pencil-alt"></i></a>'+
                                    '<a href="#del" class="delete delete-image" data-id="0" data-image="'+item+'" title="Delete"><i class="ti-close"></i></a>'+
                                '</div>'+
                                '</div>');
                        });
                    }
                    //$('#msg').html(response); // display success response from the PHP script
                },
                error: function (response) {
                    console.log(response);
                    //$('#msg').html(response); // display error response from the PHP script
                }
            });
        }
    }

    $("#file").change(function(){
        readURL(this);
    });

    $(".sfile").change(function(){
        var cimg = $(this).attr('data-id');
        readSingleURL(this, cimg);
    });

    $("#multifile").change(function(){
        //$('#multiimg').empty();
        readMultiURL(this);
    });

    $('#uploadgallery').change(function(){
        uploadGallery(this);
    });
});