<script>
<?php 
    $ci =& get_instance();
    $ci->load->helper('az_config');
?>
var theme = "<?php echo $ci->config->item('theme');?>";

function show_modal(id){
    if (theme == 'ltheme2') {
        var myModal = new bootstrap.Modal(jQuery('.az-modal-' + id), {
            keyboard: true,
            backdrop: 'static'
        });
        myModal.show();
    }
    else {
        jQuery('.az-modal-'+id).modal({
            backdrop: 'static',
            keyboard: true,
        });
    }
}
function hide_modal(id){
    if (theme == 'ltheme2') {
        var myModal = new bootstrap.Modal(jQuery('.az-modal-' + id));
        myModal.hide();
    }
    else {
        jQuery('.az-modal-'+id).modal('hide');
    }
}
function show_loading(){
    jQuery(".az-loading").show();
}

function hide_loading(){
    jQuery(".az-loading").hide();
}

function clear(idform){
    jQuery(".az-modal form#"+idform+" input").not(".x-hidden, :radio").val("");
    jQuery(".az-modal form#"+idform+" input:radio").prop('checked', false);
    jQuery(".az-modal form#"+idform+" select").not('.x-hidden').each(function(index, value) {
        if (jQuery(this).hasClass("select2-ajax")) {
            jQuery(this).val("").trigger("change");
        }
        else {
            jQuery(this).val(jQuery(this).find("option:first").val()).trigger("change");
        }
    });

    jQuery(".az-modal form#"+idform+" textarea").val("");
    var t_ckeditor = jQuery(".az-modal form#"+idform+" .ckeditor");
    jQuery(t_ckeditor).each(function(){
        var id_ckeditor = jQuery(this).attr('id');
        CKEDITOR.instances[id_ckeditor].setData('');                
    });
    var filter_table = jQuery(".filter-tabel select");
    jQuery(filter_table).each(function(){
        var fil = jQuery(this).attr("fil");
        jQuery("#"+fil).val(jQuery("#f"+fil).val());
    });

    jQuery('#l_product_name').text('-');

    jQuery(".az-modal form#"+idform+" input[type='checkbox']").prop('checked', false);
    jQuery(".az-modal form#"+idform+" input[type='radio']").prop('checked', false);

    try {
        jQuery("input[data-role='tagsinput']").tagsinput('removeAll');
    }
    catch(err){

    }
}

function edit (url, id, form, table_id, callback){
    show_loading();
    clear(form);
    $.ajax({
        type: "POST",
        url: url,
        data: {
            id: id,
        },
        success: function (response) {
            var err_message = response.err_message;
            if (err_message != undefined) {
                bootbox.alert(err_message);
            }
            else {
                var f_input = jQuery('#'+form+' input');
                var arr_ajax = [];
                var arr_azimage = [];
                jQuery.each(response[0], function(index, valu){
                    jQuery('#'+index).not("[type='file'], [type='checkbox']").val(valu).trigger("change");
                    if (jQuery('#'+index).hasClass("format-number")) {
                        jQuery('#'+index).val(thousand_separator(jQuery('#'+index).val()));
                    }
                    if (jQuery('#'+index).hasClass("format-number-minus")) {
                        jQuery('#'+index).val(thousand_separator(jQuery('#'+index).val()));
                    }
                    if (jQuery('#'+index).hasClass("format-number-decimal")) {
                        var the_separator = jQuery("#" + index).attr('data-decimal');
                        if (the_separator == undefined) {
                            the_separator = 2;
                        }
                        // var new_index = jQuery('#'+index).val().replace(/\./g, ',');
                        jQuery('#'+index).val(thousand_separator_decimal(jQuery('#'+index).val(), 2));
                    }

                    jQuery.each(jQuery("input[name='"+index+"']"), function(adata, bdata) {
                        if (jQuery(bdata).attr('type') == 'radio' || jQuery(bdata).attr('type') == 'checkbox') {
                            jQuery(bdata).prop('checked', false);
                            if (jQuery(bdata).val() == valu) {
                                jQuery(bdata).prop('checked', true);
                            }
                        }
                    });

                    try {
                        jQuery("#"+index+"[data-role='tagsinput']").tagsinput('removeAll');
                        jQuery("#"+index+"[data-role='tagsinput']").tagsinput('add', valu);
                    }
                    catch(err) {
                        
                    }

                    var ajax_ = index;

                    if (ajax_.indexOf("ajax_") >= 0) {
                        arr_ajax.push(ajax_);
                    }

                    var azimage_ = index;
                    if (azimage_.indexOf("azimage_") >= 0) {
                        arr_azimage.push(azimage_);
                    }
                });

                

                if (arr_ajax.length > 0) {
                    jQuery.each(arr_ajax, function(index_arr, value_arr) {
                        var idajax = value_arr.replace("ajax_", "");
                        if (response[0][value_arr] != null) {
                            jQuery("#"+idajax+".select2-ajax").append(new Option(response[0][value_arr], response[0][idajax], true, true)).trigger('change');
                        }
                    });
                }

                var t_area = jQuery("#"+form+' .ckeditor');
                jQuery(t_area).each(function (){
                    var id_ckeditor = jQuery(this).attr('id');
                    CKEDITOR.instances[id_ckeditor].setData(response[0][id_ckeditor]);
                });

                //azimage
                if (arr_azimage.length > 0) {
                    jQuery.each(arr_azimage, function(index_arr, value_arr) {
                        var idazimage = value_arr.replace("azimage_", "");
                        if (response[0][value_arr] != null) {
                            jQuery(".az-content-image-"+idazimage+"").attr('src', "<?php echo base_url().AZAPP;?>" + 'assets/images/member_photos/' + response[0][value_arr] + '?<?php echo strtotime(Date('YmdHis'));?>');
                            jQuery('.az-image-file-div-'+idazimage).hide();
                        }
                        else {
                            jQuery(".az-content-image-"+idazimage+"").attr('src', "<?php echo base_url().AZAPP;?>" + 'assets/images/no-image.jpg');
                            jQuery('.az-image-file-div-'+idazimage).show();      
                        }
                    });
                }
                // jQuery('.az-image-container .az-image img').attr('src', base_url + 'assets/images/no-image.jpg');
                // jQuery('.az-image-file-div').show();

                jQuery(".modal-title span").text("<?php echo azlang('Edit');?>");
                callback(response);
                
                show_modal(table_id);
            }
            hide_loading();

        },
        error: function (response) {
         hide_loading();
        },
        dataType: "json"
    });

};

function save(url, form, vtable, callback, data){
    show_loading();
    var formdata = new FormData();
   
    var txt_ckeditor = jQuery('#'+form+' .ckeditor');
    jQuery(txt_ckeditor).each(function(){
        var id_ckeditor = jQuery(this).attr("id");
        CKEDITOR.instances[id_ckeditor].updateElement();            
    });

    var data_file = jQuery('#'+form).find('input[type="file"]');
    // jQuery.each(data_file, function() {
    //     var file_id = jQuery(this).attr('id');
    //     var file_name = jQuery(this).attr('name');
    //     var file = jQuery('#'+file_id)[0].files[0];
    //     formdata.append(file_id, file);
    // });

    jQuery(data_file).each(function(adata, bdata) {
        var file_id = jQuery(bdata).attr('id');
        var file_name = jQuery(bdata).attr('name');
        var file = jQuery(bdata)[0].files[0];
        if (file_name.length > 0) {
            file_id = file_name;
        }
        formdata.append(file_id, file);
    });

    $.each(jQuery('#'+form).serializeArray(), function (a, b) {
        formdata.append(b.name, b.value);
    }); 

    if (!data) {
        data = [];
    }

    jQuery.each(data, function (ke, va) {
        formdata.append(ke, jQuery(va).val());
    });


    $.ajax({
        url: url,
        data: formdata,
        processData: false,
        contentType: false,
        type: 'POST',
        dataType: "json",
        success: function (response) {
            hide_loading();
            if (response.sMessage != "") {
                var err_response = response.sMessage;

                if (theme == 'ltheme2') {
                    Swal.fire({
                        icon: "error",
                        title: "<?php echo azlang('Error');?>",
                        text: err_response
                    });
                }
                else {
                    err_response = err_response.replace(/\n/g, "<br>");
                    bootbox.alert({
                        title: "<?php echo azlang('Error');?>",
                        message: err_response
                    });
                }
            }
            else {
                if (theme == 'ltheme2') {
                    Swal.fire({
                        icon: "success",
                        title: "<?php echo azlang('Success');?>",
                        text: "<?php echo azlang('Save data success');?>"
                    });
                }
                else {
                    bootbox.alert({
                        title: "<?php echo azlang('Success');?>",
                        message: "<?php echo azlang('Save data success');?>"
                    });
                }

                jQuery(".az-modal-" + vtable).modal("hide");
                if (theme == 'ltheme2') {
                    var dtable = jQuery('#'+vtable).DataTable({bRetrieve: true});
                    dtable.draw(false);
                }
                else {
                    var dtable = jQuery('#'+vtable).dataTable({bRetrieve: true});
                    dtable.fnDraw(false);
                }
                callback(response);
            }
        },
        error: function (response) {
            console.log(response);
            hide_loading();
        }
    });
}

function remove(url, id, vtable, callback){
    if (theme == 'ltheme2') {
        Swal.fire({
            title: "<?php echo azlang('Are you sure for delete?');?>",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#d33",
            cancelButtonColor: "#999b9d",
            confirmButtonText: "<?php echo azlang('Delete');?>"
        }).then((result) => {
            if (result.isConfirmed) {
                go_delete(url, id, vtable, callback)
            }
        });
    }
    else {
        bootbox.confirm({
            title: "<?php echo azlang('Delete data');?>",
            message: "<?php echo azlang('Are you sure for delete?');?>",
            callback : function(result) {
                if (result == true) {
                    go_delete(url, id, vtable, callback);
                }
            }
        });
    }

}

function go_delete(url, id, vtable, callback) {
    $.ajax({
        url: url,
        type: "post",
        dataType: "json",
        data: {
            id: id
        },
        success: function (response) {
            if (response.err_code > 0) {
                bootbox.alert({
                    title: "<?php echo azlang('Error');?>",
                    message: response.err_message
                });
            }
            else {
                if (theme == 'ltheme2') {
                    var dtable = jQuery('#'+vtable).DataTable({bRetrieve: true});
                    dtable.draw(false);
                }
                else {
                    var dtable = jQuery('#'+vtable).dataTable({bRetrieve: true});
                    dtable.fnDraw(false);
                }
                callback(response);
            }
        },
        error: function (er) {
            bootbox.alert({
                title: "<?php echo azlang('Error');?>",
                message: "<?php echo azlang('Delete data failed');?> "+er
            });
        }
    });
}

function thousand_separatorx(x){
    if (x == null) {
        return x;
    }
    if(typeof x !== 'undefined') {
        return x.toString().replace(/\./g, '').replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    }
}

function thousand_separator_ori(x) {
    if (x == null) {
        return x;
    }
    if(typeof x !== 'undefined') {
        x = x.toString().replace(/\./g, '');
        var n= x.toString().split(",");
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        return n.join(",");
    }
}

var format_number = ".";
var format_decimal = ",";
var db_format_decimal = "<?php echo az_get_config('decimal_format');?>";
if (db_format_decimal == ".") {
    format_decimal = ".";
    format_number = ",";
}

function thousand_separator(x) {
    if (x == null) {
        return x;
    }
    if(typeof x !== 'undefined') {
        x = parseInt(x);
        x = x.toString().replace(new RegExp('\\' +format_number, 'g'), '');
        var n= x.toString().split(format_decimal);
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, format_number);
        return n.join(format_decimal);
    }
}
    
function thousand_separator_decimal_ori(x, y) {
    if (x == null) {
        return x;
    }
    if (y == null) {
        y = 2;
    }
    if(typeof x !== undefined) {
        if (x == '') {
            x = 0;
        }
        new_x = parseFloat(x).toFixed(y);
        new_x = new_x.toString().replace(/\./g, ',');
        var n = new_x.toString().split(",");
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        var ret = n.join(",");
        return ret;
    }
}

function thousand_separator_decimal(x, y) {
    if (x == null) {
        return x;
    }
    if (y == null) {
        y = 2;
    }
    if(typeof x !== undefined) {
        if (x == '') {
            x = 0;
        }
        new_x = parseFloat(x).toFixed(y);
        new_x = new_x.toString().replace(new RegExp('\\' + format_number, 'g'), format_decimal);

        var n = new_x.toString().split(format_decimal);
        n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, format_number);
        var ret = n.join(format_decimal);
        return ret;
    }
}

function get_thousand_separator_decimal(x) {
     if (x == null) {
        return x;
    }
    if(typeof x !== 'undefined') {
        var x = x.toString().replace(/\./g, ',');
        return thousand_separator_decimal(x);
    }
}

function remove_separator(x){
    if (x == null) {
        return x;
    }
    if(typeof x !== 'undefined') {
        if (format_decimal == '.') {
            var new_x = x.toString().replace(/\,/g, '');
        }
        else {
            var new_x = x.toString().replace(/\./g, '');
            new_x = new_x.toString().replace(/\,/g, '.');            
        }
        return new_x;
        // return x.toString().replace(/\./g, '');
    }
}

function remove_dot(x) {
    if (x == null) {
        return x;
    }
    if (typeof x !== 'undefined') {
        return x.toString().replace(/\./g, '');
    }
}


//if CSRF TRUE
<?php 
    $ci =& get_instance();
    $csrf = $ci->config->item('csrf_protection');
    if ($csrf) {
?>

jQuery("body form").append('<input class="x-hidden" type="hidden" name="<?php echo $ci->security->get_csrf_token_name();?>" value="<?php echo $ci->security->get_csrf_hash();?>">');

csrf_token_name = "<?php echo $ci->security->get_csrf_token_name(); ?>";
csrf_cookie_name = "<?php echo $ci->config->item('csrf_cookie_name'); ?>";
jQuery(function (jQuery) {
    // this bit needs to be loaded on every page where an ajax POST 
    var object = {};
    object[csrf_token_name] = jQuery.cookie(csrf_cookie_name);
    jQuery.ajaxSetup({
        data: object
    });
    $(document).ajaxComplete(function () {
        object[csrf_token_name] = jQuery.cookie(csrf_cookie_name);
        jQuery.ajaxSetup({
            data: object
        });
        jQuery("input[name='"+csrf_token_name+"']").val(jQuery.cookie(csrf_cookie_name));
    });
});

<?php
    }
?>

function az_reload_csrf() {
    setTimeout(function() {
        jQuery('input[name=\"'+csrf_token_name+'\"]').val(jQuery.cookie(csrf_cookie_name));
    }, 1000);
}


jQuery(document).ready(function(){
    try {
        jQuery("select.select").select2(); 
    }
    catch(e) {
        
    }
    $.fn.modal.Constructor.prototype.enforceFocus = function() {};
    
    jQuery("body").append(jQuery(".az-modal"));

    jQuery('.az-modal').on('shown.bs.modal', function () {
        jQuery('input:text:visible:first', this).not('.x-hidden, .x-focus').focus();
    });  

    jQuery(document).on('show.bs.modal', '.modal', function () {
        var zIndex = 1040 + (10 * jQuery('.modal:visible').length);
        $(this).css('z-index', zIndex);
        setTimeout(function() {
            jQuery('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
        }, 0);
    });

    jQuery(document).on('hidden.bs.modal', '.modal', function () {
        jQuery('.modal:visible').length && jQuery(document.body).addClass('modal-open');
    });

    jQuery("body").on("change", ".filter-table select", function(){
        var table_id = jQuery(".filter-tabel").attr("tid");
        var dtable = jQuery('#'+table_id).dataTable({bRetrieve: true});
        dtable.fnDraw(false);
    });

    jQuery('.az-form').on('keyup keypress', function(e) {
      var keyCode = e.keyCode || e.which;
      if (keyCode === 13) { 
        if(event.target.tagName != 'TEXTAREA') {
            e.preventDefault();
            return false;
        }
      }
    });

    //setup before functions
    var typingTimer;                //timer identifier
    var doneTypingInterval = 4000;  //time in ms, 5 second for example
    <?php 
        $typing_interval = $ci->config->item('typing_interval');
    ?>
    var config_interval = "<?php echo $typing_interval;?>";
    if (config_interval != "") {
        doneTypingInterval = config_interval;
    }


    jQuery("body").on('keyup keydown', '.format-number', function(e){
        jQuery(this).val(thousand_separator(jQuery(this).val()));
        console.log(e.keyCode);
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || 
            // Allow: Ctrl+V
            (e.keyCode == 86 && ( e.ctrlKey === true || e.metaKey === true ) ) || 
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

    jQuery("body").on('keydown keyup', '.format-number-decimal', function(e) {
        var the = jQuery(this);
        var decimal = jQuery(this).attr('data-decimal');
        if (decimal == undefined) {
            decimal = 2;
        }
        clearTimeout(typingTimer);
        typingTimer = setTimeout(function() {
            var new_val = remove_separator(the.val());
            the.val(thousand_separator_decimal(new_val, decimal));
        }, doneTypingInterval);


        var key_decimal = [46, 8, 9, 27, 13];
        if (format_decimal == '.') {
            key_decimal.push(110);
            key_decimal.push(190);
        }
        else {
            key_decimal.push(188);
        }

        if ($.inArray(e.keyCode, key_decimal) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || 
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

    // jQuery("body").on('keyup', '.format-number-decimal', function(e){
    //     var the = jQuery(this);
    //     clearTimeout(typingTimer);
    //     typingTimer = setTimeout(function() {
    //         the.val(thousand_separator_decimal(the.val()));
    //     }, doneTypingInterval);
    // });

    jQuery("body").on('keyup keydown', '.format-number-minus', function(e){
        jQuery(this).val(thousand_separator(jQuery(this).val()));
        if ($.inArray(e.keyCode, [189, 46, 8, 9, 27, 13, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || 
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

    jQuery("body").on('keyup keydown', '.format-phone', function(e){
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || 
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });

    jQuery(document).on( 'click', '.az-table tbody tr td', function (event) {
        var btn = jQuery(this).find('button');
        if (btn.length == 0) {
            jQuery(this).parents('tr').toggleClass('selected');
        }
    });
});