/**
* @package com_spbooking
* @author JoomShaper http://www.joomshaper.com
* @copyright Copyright (c) 2010 - 2023 JoomShaper
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
*/

(function( $ ) {

    $.fn.spmodal = function(options)
    {
        var options = $.extend({
            saveTrigger: '#applyBtn'
        }, options);

        return this.each(function()
        {
            const saveTrigger   = options.saveTrigger;

            $(function(){
                //Css
                let group = $('.spmodal-save').parent().parent().parents('div.control-group');

                let reloadGroup = group.prev();
                
                //group.css({display: 'inline-block', width: '100px'});
                //reloadGroup.css({display: 'inline-block'});
                group.find('.controls').css({margin: '0', 'margin-left': '5px'});

                $(document).on('click', '.spmodal-save', function(e) {

                    let reloadHolder = $(this).closest('.modal').prev();
                    
                    let reloaderData = (typeof reloadHolder.data('reloader') == "undefined") ? reloadHolder.data('bs-reloader') : reloadHolder.data('reloader');

                    let reloadId = "#jform_" + reloaderData;

                    let controlGroup = $(this).parents('div.control-group');
                    let holderGroup = controlGroup.prev();
                    let reload = holderGroup.find(reloadId);

                    let modal = $(this).closest('.modal');
    
                    modal.find("iframe").contents().find(saveTrigger).click();
                    
                    setTimeout(() => {
                        $(reloadId).load(window.location.href + " " + reloadId + " > *");
                    }, 100);
                    
                    setTimeout(() => {
                        console.log(modal.find("iframe").contents().find('#system-message-container').find('joomla-alert')[0].getAttribute('type'))
                        if (modal.find("iframe").contents().find('joomla-alert')[0].getAttribute('type') != "danger")
                        {
                            modal.modal('hide');
                        }
                    }, 1000);
                });
            });
        });
    }

})( jQuery );