/* 
 * *************************************************
 * Copyright (C) 2020 Earworks.                    *
 * Codeigniter Project Template Modification       *
 * Please contact our email for more information : *
 * contact@earworks.co.id                          *
 * *************************************************
 */
var customJcrop = function () {
    var the;
    var jcrop_api = [],
            obj_list = [],
            blobImg = [],
            boundx = [],
            boundy = [],
            active;
    return{
        init: function () {
            the = this;
            $('.btn-upload').each(function () {
                $(this).change(function (e) {
                    the.preview(this, e);
                });
            });
        },
        preview: function (obj, e) {
            active = $(obj).attr('name');
            obj_list[active] = $(obj);
            if (obj.files && obj.files[0]) {

                var reader = new FileReader();
                reader.onload = function (e) {
                    blobImg[active] = e.target.result;
                    if (jcrop_api && jcrop_api[active]) {
                        obj_list[active].parent().find('.custom-jcrop .jcrop-holder').show();
                        obj_list[active].parent().find('.img-preview').hide();
                        obj_list[active].parent().find('.btn-crop').hide();
                        obj_list[active].parent().find('.btn-recrop').hide();
                        jcrop_api[active].setImage(blobImg[active]);
                    } else {
                        var cropper = obj_list[active]
                                .parent()
                                .find('.img-cropper');
                        cropper.attr('src', blobImg[active]);
                        cropper.Jcrop({
                            aspectRatio: obj_list[active].data('ratio1') / obj_list[active].data('ratio2'),
                            bgFade: true,
                            bgOpacity: .2,
                            allowSelect: false,
                            setSelect: [50, 50, 200, 200],
                            onSelect: function (data) {
                                active = $(obj).attr('name');
                                the.updateCoords(obj_list[active], data);
                            },
                            onChange: function (data) {
                                active = $(obj).attr('name');
                                the.updateCoords(obj_list[active], data);
                            }
                        }, function () {
                            jcrop_api[active] = this;
                            boundx[active] = jcrop_api[active].getBounds()[0];
                            boundy[active] = jcrop_api[active].getBounds()[1];
                            obj_list[active].parent().find('input[name*=\'_boundw\']')
                                    .val(boundx[active]);
                            obj_list[active].parent().find('input[name*=\'_boundh\']')
                                    .val(boundy[active])
                        });

                    }
                };
                reader.readAsDataURL(obj.files[0]);
            }
        },
        updateCoords: function (obj, data) {
            var parent = obj.parent();
            parent.find('input[name*=\'_x\']').val(data.x);
            parent.find('input[name*=\'_x2\']').val(data.x2);
            parent.find('input[name*=\'_y\']').val(data.y);
            parent.find('input[name*=\'_y2\']').val(data.y2);
            parent.find('input[name*=\'_w\']').val(data.w);
            parent.find('input[name*=\'_h\']').val(data.h);

            var cropBtn = parent.find('.btn-crop');
            var cropPreview = parent.find('.img-preview');
            var reCropBtn = parent.find('.btn-recrop');
            cropBtn.show();
            cropBtn.one('click', function () {
                var img = $('<img>', {src: blobImg[obj.attr('name')]}).css({
                    top: '-' + data.y + 'px',
                    left: '-' + data.x + 'px',
                    width: boundx[obj.attr('name')] + 'px',
                    height: boundy[obj.attr('name')] + 'px'});

                cropPreview
                        .css({
                            'width': data.w,
                            'height': data.h
                        })
                        .empty().append(img)
                        .show();
                $(this).hide();
                parent.find('.custom-jcrop .jcrop-holder').hide();
                reCropBtn.show();
            });
            reCropBtn.one('click', function () {
                cropPreview.hide();
                $(this).hide();
                parent.find('.custom-jcrop .jcrop-holder').show();
            });
        }
    };
}();

var script = function () {
    var the;
    return {
        init: function () {
            the = this;
//            the.handleMenu();
            the.handlePageModal();
            the.handleNote();
            the.handleDatePicker();
            the.handleLazyLoad();
            $(".nav-tabs a[data-toggle=tab]").on("click", function (e) {
                if ($(this).parent().hasClass("disabled")) {
                    e.preventDefault();
                    return false;
                }
            });
        },
        handleLazyLoad: function () {
            if ($('.lazy-load').length !== 0) {
                $('.lazy-load').lazy();
            }
        },
        handleMenu: function () {
            // jQuery for page scrolling feature - requires jQuery Easing plugin
            $('a.page-scroll').bind('click', function (event) {
                var $anchor = $(this);
                $('html, body').stop().animate({
                    scrollTop: ($($anchor.attr('href')).offset().top - 50)
                }, 1250, 'easeInOutExpo');
                $(".navbar-collapse").collapse('hide');
                event.preventDefault();
            });
            // Select all links with hashes
            $('a[href*="#"]')
                    // Remove links that don't actually link to anything
                    .not('[href="#"]')
                    .not('[href="#0"]')
                    .click(function (event) {
                        // On-page links
                        if (
                                location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
                                &&
                                location.hostname == this.hostname
                                ) {
                            // Figure out element to scroll to
                            var target = $(this.hash);
                            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                            // Does a scroll target exist?
                            if (target.length) {
                                // Only prevent default if animation is actually gonna happen
                                event.preventDefault();
                                $('html, body').animate({
                                    scrollTop: target.offset().top - 90
                                }, 1000, function () {
                                    // Callback after animation
                                    // Must change focus!
                                    var $target = $(target);
                                    if ($target[0].length !== 0) {
                                        $('a.page-scroll').each(function () {
                                            $(this).parent().removeClass('active');
                                        });
                                        var focusObj = $($target[0]).attr('id');
                                        var activeLink = $('.navbar-custom').find('a[href=\'#' + focusObj + '\']').parent();
                                        if (activeLink.length !== 0) {
                                            activeLink.addClass('active');
                                        }
                                    }
                                    $target.focus();
                                    if ($target.is(":focus")) { // Checking if the target was focused
                                        return false;
                                    } else {
                                        $target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
                                        $target.focus(); // Set focus again
                                    }
                                    ;
                                });
                            }
                        }
                    });
            $(window).scroll(function () {
                if ($(window).scrollTop() > 80) {
                    $('.navbar-custom').addClass('after-scroll');
                } else {
                    $('.navbar-custom').removeClass('after-scroll');
                }
            });
        },
        handlePageModal: function () {
            if ($('.page-modal').length === 0) {
                return;
            }
            $('.page-modal').each(function () {
                $(this).click(function () {
                    the.handleRedirectModal(this);
                });
            });
        },
        handleRedirectModal: function (obj) {
            $.ajax({
                url: $(obj).data('ref'),
                type: 'GET',
                dataType: 'HTML',
                success: function (res) {
                    console.log($('.modal-form').length);
                    $('.modal-form').find('.modal-content').empty().html(res);
                    $('.modal-form').modal('show');
                }
            });
        },
        handleNote: function () {
            $('.message').each(function (index, value) {
                setTimeout(function () {
                    $(value).addClass('open');
                }, 500 * (index + 1));
                setTimeout(function () {
                    $(value)
                            .css('opacity', 0)
                            .css('height', 0).remove();
                }, 10000 + (500 * (index + 1)));
            });
            $('.close-message').click(function () {
                $(this).parent()
                        .css('opacity', 0)
                        .css('height', 0);
            });
        },
        handleDatePicker: function () {
            if ($('.datepicker').length !== 0) {
                $('.datepicker').each(function () {
                    $(this).attr('readonly', 'readonly');
                    $(this).datepicker({
                        changeYear: true,
                        changeMonth: true,
                        dateFormat: "dd-mm-yy",
                        maxDate: $(this).data('maxdate'),
                        minDate: $(this).data('mindate'),
                        defaultDate: $(this).val(),
                    });
                });
            }
        },
    };
}();
$(document).ready(function () {
    script.init();
});