<?php
// LIGTBOXES SWITCH

///////////////////////////////////////////
// scripts and styles
function gg_lightbox_scripts() {
	if(is_admin()) {
        return false;
    }
	$lightbox = get_option('gg_lightbox', 'lcweb');
    $generic_versioning = GG_VER;
    
	switch($lightbox) {
		case 'lcweb':
		default		:
			$css_path = '/lc-lightbox/css/lc_lightbox.min.css';
			$js_path = '/lc-lightbox/js/lc_lightbox.gg.min.js';
			
			wp_enqueue_style('gg-lcl-skin', GG_URL .'/js/lightboxes/lc-lightbox/skins/'. get_option('gg_lb_lcl_style', 'minimal') .'.css', 99, '1.4.1');
			wp_enqueue_script('gg-lb-alloyfinger', GG_URL .'/js/lightboxes/lc-lightbox/lib/alloy_finger.min.js', 999, '1.3.0', true);
			break;
			
        case 'photoswipe':
			$css_path = '/photoswipe/photoswipe.css';
			$js_path = '/photoswipe/photoswipe.umd.min.js';
            
			wp_enqueue_script('gg-pswp-ui', GG_URL .'/js/lightboxes/photoswipe/photoswipe-lightbox.umd.min.js', 99, GG_VER, true);
			break;    
            
		case 'lightcase':
			$css_path = '/lightcase/src/css/lightcase.min.css';
			$js_path = '/lightcase/src/js/lightcase.min.js';
			
			wp_enqueue_script('gg-lb-jquerytouch', GG_URL .'/js/lightboxes/lightcase/vendor/jQuery/jquery.events.touch.min.js', 99, GG_VER, true);
			break;	
		
		case 'simplelb':
			$css_path = '/simplelightbox/simplelightbox.min.css';
			$js_path = '/simplelightbox/simple-lightbox.min.js';
			break;
			
		case 'lightgall':
			$css_path = '/lightGallery/css/lightgallery.css';
			$js_path = '/lightGallery/js/lightgallery.min.js';
			break;
			
		case 'mag_popup':
			$css_path = '/magnific-popup/magnific-popup.css';
			$js_path = '/magnific-popup/magnific-popup.pckg.js';
			break;
			
		case 'imagelb':
			$css_path = '/imageLightbox/imagelightbox.min.css';
			$js_path = '/imageLightbox/imagelightbox.min.js';
			break;	
		
		case 'photobox':
			$css_path = '/photobox/photobox.css';
			$js_path = '/photobox/jquery.photobox.min.js';
			break;		
	}
	
	wp_enqueue_style('gg-lightbox-css', GG_URL .'/js/lightboxes'. $css_path, 90, $generic_versioning);
	wp_enqueue_script('gg-lightbox-js', GG_URL .'/js/lightboxes'. $js_path, 100, $generic_versioning, true);
    
    wp_add_inline_script('gg-lightbox-js', 
        str_replace(array("\r", "\n", "\t", "\v"), '', gg_throw_lb_code())
    );
}
add_action('wp_enqueue_scripts', 'gg_lightbox_scripts');




/////////////////////////////////////////////
// footer inline codes
function gg_throw_lb_code() {
	$lightbox = get_option('gg_lightbox', 'lcweb');
	
	
    $code = '
    let lcl_gg_prepare,
        lcl_gg_nulling_prepare, 
        gg_ptb_executed;';
        
    // LCweb LB trick - launch any gallery / slider / carousel to prepare elements and allow deeplinking
    if($lightbox == 'lcweb' && get_option('gg_lb_deeplink')) {
        $code .= "
        window.gg_lcl_allow_deeplink = function() {
            if(typeof(gg_no_lb) != 'undefined') {
                return false;	
            }
            const $ = jQuery;

            if(lcl_gg_nulling_prepare) {
                clearTimeout(lcl_gg_nulling_prepare);
            }
            lcl_gg_prepare = true; 

            $('.gg_carousel_wrap, .gg_container:not(.gg_coll_container)').each(function() {
                $(this).find('.gg_img:not(.gg_linked_img, .gg_excluded_img)').first().trigger('click');
            });
            $('.galleria-gg-lightbox').each(function() {
                $(this).trigger('click');
            });
        };
        jQuery(document).ready(function($) {
            gg_lcl_allow_deeplink();
        });";
    }

    // thumbs maker
    $code .= "
    const gg_lb_thumb = function(src) {";
    
        if(get_option('gg_use_timthumb')) {
            $code .= "'". esc_js(GG_TT_URL) ."?src='+ encodeURIComponent(src) +'&w=100&h=100'";
        } else {
            $code .= "'". esc_js(GG_URL) ."/classes/easy_wp_thumbs.php?src='+ encodeURIComponent(src) +'&w=100&h=100'";
        }

    $code .= "
    };";

        
        
    // GG LC lightbox options available for everyone
    if($lightbox == 'lcweb') {
        $tm_url = false;
        if(!get_option('gg_lb_thumbs_full_img')) {
            $tm_url = (get_option('gg_use_timthumb')) ? GG_TT_URL .'?src=%URL%&w=%W%&h=%H%&q=80' : GG_EWPT_URL .'?src=%URL%&w=%W%&h=%H%&q=80';
        } 

        // comments object
        switch(get_option('gg_lb_lcl_comments')) {
            case 'disqus' :
                $comm_obj = wp_json_encode(array(
                    'type' => 'disqus',
                    'shortname' => (string)get_option('gg_lcl_disqus_shortname', '')
                ));
                break;

            case 'fb' :
                $comm_obj = wp_json_encode(array(
                    'type' => 'facebook',
                    'style' => (get_option('gg_lb_lcl_style', 'minimal') == 'light') ? 'light' : 'dark'
                ));
                break;

            default :
                $comm_obj = 'false';
                break;	
        }
        
        $code .= "
        window.gg_lcl_config = {
            deeplink 		: ". ((get_option('gg_lb_deeplink')) ? 'true' : 'false') .",
            img_zoom        : " . ((get_option('gg_lb_zoom')) ? 'true' : 'false') . ",
            global_type     : 'image',
            wrap_class      : '" . esc_js(get_option('gg_lb_lcl_openclose', 'lcl_zoomin_oc')) . "',
            author_by_txt   : `" . esc_html(get_option('gg_lcl_author_by_txt', 'by')) . "`,

            slideshow       : true,
            open_close_time : " . absint(get_option('gg_lb_oc_time', 500)) . ",
            animation_time  : " . absint(get_option('gg_lb_time', 400)) . ",
            slideshow_time  : " . absint(get_option('gg_lb_ss_time', 4000)) . ",
            autoplay        : " . ((!get_option('gg_lb_slideshow')) ? 'false' : 'true') . ",
            counter         : " . ((get_option('gg_lb_counter')) ? 'true' : 'false') . ",
            progressbar     : " . ((get_option('gg_lb_progressbar')) ? 'true' : 'false') . ",

            max_width       : '" . absint(get_option('gg_lb_max_w', 90)) . "%',
            max_height      : '" . absint(get_option('gg_lb_max_h', 90)) . "%',
            ol_opacity      : " . (absint(get_option('gg_lb_opacity', 70)) / 100) . ",
            ol_color        : '" . esc_js(get_option('gg_lb_ol_color', '#111')) . "',
            ol_pattern      : " . ((get_option('gg_lb_ol_pattern', 'none') == 'none') ? 'false' : "'" . str_replace('pattern-', '', esc_html(get_option('gg_lb_ol_pattern'))) . "'") . ",
            border_w        : " . absint(get_option('gg_lb_border_w')) . ",
            border_col      : '" . esc_js(get_option('gg_lb_border_col', '#666')) . "',
            padding         : " . absint(get_option('gg_lb_padding')) . ",
            radius          : " . absint(get_option('gg_lb_radius')) . ",

            shadow          : " . ((get_option('gg_lb_use_shadow')) ? 'true' : 'false') . ",
            remove_scrollbar: false,
            skin            : '" . esc_js(get_option('gg_lb_lcl_style', 'minimal')) . "',

            data_position   : '" . esc_js(get_option('gg_lcl_txt_pos', 'under')) . "',
            cmd_position    : '" . esc_js(get_option('gg_lb_cmd_pos', 'inner')) . "',
            ins_close_pos   : '" . ((get_option('gg_lb_corner_close')) ? 'corner' : 'normal') . "',
            nav_btn_pos     : '" . ((get_option('gg_lb_middle_nav_pos')) ? 'middle' : 'normal') . "',

            txt_hidden      : " . absint(get_option('gg_lb_txt_treshold', 500)) . ",

            thumbs_nav      : " . ((!get_option('gg_lb_thumbs')) ? 'false' : 'true') . ",
            tn_hidden       : " . absint(get_option('gg_lb_tn_treshold', 500)) . ",
            thumbs_w        : " . absint(get_option('gg_lb_thumb_w', 110)) . ",
            thumbs_h        : " . absint(get_option('gg_lb_thumb_h', 110)) . ",
            thumbs_maker_url: " . (($tm_url) ? '`' . esc_html($tm_url) . '`' : 'false') . ",

            fullscreen      : " . ((!get_option('gg_lb_fullscreen')) ? 'false' : 'true') . ",
            fs_only         : " . absint(get_option('gg_lb_fs_treshold', 500)) . ",

            socials         : " . ((!get_option('gg_lb_socials')) ? 'false' : 'true') . ",
            fb_share_params : " . ((!get_option('gg_lb_lcl_direct_fb') || !function_exists('lcsism_share_url')) 
                                    ? 'false' 
                                    : "'app_id=". esc_js(get_option('gg_lcl_fb_appid')) ."&redirect_uri=". esc_js(lcsism_redirect_url()) . "&lcsism_img=%IMG%&lcsism_title=%TITLE%&lcsism_descr=%DESCR%'" ) .",

            comments        : " . (($comm_obj == 'false') ? 'false' : "JSON.parse(`". $comm_obj ."`)") . ",
            download        : " . ((!get_option('gg_lb_download')) ? 'false' : 'true') . ",
            touchswipe      : " . ((get_option('gg_lb_no_touchswipe')) ? 'false' : 'true') . ",
            rclick_prevent  : " . ((get_option('gg_disable_rclick')) ? 'true' : 'false') . ",";

            if(get_option('gg_lb_download')) {
                $code .= "
                html_is_ready : function(e, vars) {

                    if(typeof(vars) != 'undefined') {
                        jQuery.each(vars.elems, function(i,v) {
                            v.download = v.src;
                        });
                    }
                }";
            }
        
        $code .= "
        };";
    }
     


    // throw lightbox 
    $code .= "
    window.gg_throw_lb = function(gall_obj, rel, clicked_index, no_deeplink) {
        if(!Object.keys(gall_obj).length) {
            return false;
        }
        const $ = jQuery;

        ($('#gg_lb_gall').length) ? $('#gg_lb_gall').empty() : $('body').append(`<div id='gg_lb_gall'></div>`);";

        switch($lightbox) : 
            case 'lcweb' : // LCwb lightbox
            default :
    
                $code .= "
                if(typeof(gg_no_lb) != 'undefined') {
                    return false;	
                }
                
                let sel_img = [];
                $.each(Object.keys(gall_obj), function(i, v) {	
                    var obj = gall_obj[v];
                    var o = {
                        src				: obj.img,
                        title			: obj.title,
                        txt				: obj.descr,
                        author			: obj.author,
                        canonical_url	: '". (($comm_obj == 'false') ? 'false' : esc_js(site_url()) ) ."?lcl_canon=' + encodeURIComponent(obj.img)
                    };
                    sel_img.push(o);
                });

                let config = {...window.gg_lcl_config};
                if(config.deeplink && typeof(no_deeplink) != 'undefined' && no_deeplink) {
                    config.deeplink = false;   
                }
                const lcl_obj = lc_lightbox(sel_img, config);

                if(no_deeplink || typeof(lcl_gg_prepare) == 'undefined' || !lcl_gg_prepare) {
                    lcl_open(lcl_obj, clicked_index);
                }
                else {
                    if(typeof(lcl_gg_nulling_prepare) != 'undefined') {
                        clearTimeout(lcl_gg_nulling_prepare);
                    }
                    lcl_gg_nulling_prepare = setTimeout(function() {
                        lcl_gg_prepare = false;
                    }, 150);
                }";
            break;


            case 'photoswipe' : // PHOTOSWIPE	

                // append mandatory code
                $code .= '
                const pswp_elements = 
                      `<div class="gg_pswp pswp" tabindex="-1" role="dialog" aria-hidden="true"><!-- Background of PhotoSwipe. It is a separate element as animating opacity is faster than rgba(). --> <div class="pswp__bg"></div><div class="pswp__scroll-wrap"><!-- Container that holds slides. PhotoSwipe keeps only 3 of them in the DOM to save memory. Do not modify these 3 pswp__item elements, data is added later on. --> <div class="pswp__container"> <div class="pswp__item"></div><div class="pswp__item"></div><div class="pswp__item"></div></div><div class="pswp__ui pswp__ui--hidden"> <div class="pswp__top-bar"> <div class="pswp__counter"></div><button class="pswp__button pswp__button--close" title="Close (Esc)"></button> <button class="pswp__button pswp__button--share" title="Share"></button> <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button> <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button> <div class="pswp__preloader"> <div class="pswp__preloader__icn"> <div class="pswp__preloader__cut"> <div class="pswp__preloader__donut"></div></div></div></div></div><div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"> <div class="pswp__share-tooltip"></div></div><button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"> </button> <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"> </button> <div class="pswp__caption"> <div class="pswp__caption__center"></div></div></div></div></div>`;

                if(!$(".gg_pswp").length) {
                    $("body").append(pswp_elements);
                }
                const $pswp = $(".gg_pswp")[0];


                // prepare images array
                let sel_img = [];
                $.each(Object.keys(gall_obj), function(i, v) {	
                    var obj = gall_obj[v];
                    var txt = (obj.descr) ? `<p class="gg_lb_p_margin"><strong>`+ obj.title +`</strong></p>`+ obj.descr : obj.title;

                    var o = {
                        true_src: obj.img,
                        src	    : obj.img,
                        width   : 1,
                        height  : 1,
                        alt     : txt
                    };
                    sel_img.push(o);
                });

                // defining options
                let options = {
                    dataSource  : sel_img, 
                    bgOpacity   : '. (absint(get_option('gg_lb_opacity')) / 100) .',
                    showHideAnimationType: "fade",
                    pswpModule: PhotoSwipe,

                    paddingFn: (viewportSize, itemData, index) => {
                        const horiz_padd = Math.round( (viewportSize.x - viewportSize.x * '. (absint(get_option('gg_lb_max_w', 100)) / 100) .') / 2),
                              vert_padd = Math.round( (viewportSize.y - viewportSize.y * '. (absint(get_option('gg_lb_max_h', 100)) / 100) .') / 2);

                        return {
                            top: vert_padd,
                            bottom: vert_padd,
                            left: horiz_padd,
                            right: horiz_padd
                        };
                    },
                };';

                if(!get_option('gg_lb_zoom')) {
                    $code .= "
                    options.zoom = false;
                    options.imageClickAction = 'next';
                    options.tapAction = 'next';";
                }

                if(!get_option('gg_lb_counter')) {
                    $code .= "options.counter = false;";
                }

                $code .= "
                const gallery = new PhotoSwipeLightbox(options);

                // fix to not specify image sizes
                gallery.on('contentLoad', function(content) {
                    let item = content.content;

                    if(item.height < 2 || item.width < 2) {
                        let img = new Image();

                        if(!content.isLazy) {
                            $('.pswp.pswp--open').addClass('gg_pswp_loader');
                        }

                        img.onload = function() {
                            gallery.options.dataSource[item.index] = {
                                src     : item.data.src, 
                                width   : img.width,
                                height  : img.height,
                                alt     : item.data.alt,
                            };

                            if(gallery.pswp) {
                                if(!content.isLazy) {
                                    $('.pswp.pswp--open').removeClass('gg_pswp_loader');
                                }

                                gallery.pswp.refreshSlideContent(item.index);
                            }
                        };

                        img.src = item.data.src
                    }
                });
                gallery.init();
                gallery.loadAndOpen(clicked_index);";
                break;


            case 'lightcase' : // LIGHTCASE - min jQuery 1.7 	
                $code .= '
                $.each(Object.keys(gall_obj), function(i, v) {
                    var obj = gall_obj[v];
                    $("#gg_lb_gall").append(`<a href="`+ obj.img +`" title="`+ obj.title +`" data-rel="lightcase:`+ rel +`">`+ obj.descr +`</a>`);
                });

                $(`#gg_lb_gall > a`).lightcase({
                    transition        : `' . esc_js(get_option('gg_lightcase_anim_behav', 'scrollHorizontal')) . '`,
                    speedIn           : ' . absint(get_option('gg_lb_time', 400)) . ',
                    speedOut          : ' . absint(get_option('gg_lb_time', 400)) . ',
                    maxWidth          : `' . absint(get_option('gg_lb_max_w', 90)) . '%`,
                    maxHeight         : `' . absint(get_option('gg_lb_max_h', 90)) . '%`,
                    overlayOpacity    : ' . ((int)get_option('gg_lb_opacity', 70) / 100) . ',
                    slideshow         : true,
                    slideshowAutoStart: ' . ((!get_option('gg_lb_slideshow')) ? 'false' : 'true') . ',
                    timeout           : ' . absint(get_option('gg_lb_ss_time', 4000)) . ',
                    type              : `image`
                });
                
                $(`#gg_lb_gall > a:eq(`+ clicked_index +`)`).trigger("click");
                $("#lightcase-overlay").addClass("gg_lc_ol");';
                break;

    
            case 'simplelb' : // SIMPLE LIGHTBOX - doesn't work with images not specifying extension
                $code .= '
                $.each(Object.keys(gall_obj), function(i, v) {
                    var obj = gall_obj[v];
                    var txt = (obj.descr) ? `<p class="gg_lb_p_margin"><strong>`+ obj.title +`</strong></p>`+ obj.descr : obj.title;

                    $("#gg_lb_gall").append(`<a href="`+ obj.img +`"><img src="" title="`+ gg_lb_html_fix(txt) +`" /></a>`);
                });

                new SimpleLightbox("#gg_lb_gall > a", {
                    showCounter     : false,
                    fileExt         : false,
                    history         : false,
                    animationSpeed      : ' . absint(get_option('gg_lb_time', 400)) . ',
                    animationSlide      : ' . ((get_option('gg_lb_anim_behav', 'slide') == 'slide') ? 'true' : 'false') . ',
                    widthRatio          : ' . (absint(get_option('gg_lb_max_w', 80)) / 100) . ',
                    heightRatio         : ' . (absint(get_option('gg_lb_max_h', 90)) / 100) . ',
                    disableRightClick   : ' . ((get_option('gg_disable_rclick')) ? 'true' : 'false') . ',
                    className: `gg_simplelb`
                });

                $(`#gg_lb_gall > a:eq(`+ clicked_index +`)`)[0].click();
                $(".sl-overlay").addClass("gg_simplelb");';
                break;
    
    
        case 'mag_popup' : // MAGNIFIC POPUP
            $code .= '
            let ggmp_size_check,
                sel_img = [];

            $.each(Object.keys(gall_obj), function(i, v) {	
                var obj = gall_obj[v];
                var txt = (obj.descr) ? `<p class="gg_lb_p_margin"><strong>`+ obj.title +`</strong></p>`+ obj.descr : obj.title;

                var o = {src : obj.img, type : "image", title : txt};
                sel_img.push(o);
            });

            $.magnificPopup.open({
                tLoading: `<span class="gg_mag_popup_loader"></span>`,
                mainClass: "gg_mp",
                removalDelay: 300,
                gallery: {
                    enabled: true,
                    navigateByImgClick: true,
                    preload: [1,1]
                },
                callbacks: {
                    beforeClose: function() {
                      $(document).find(".mfp-figure").stop().fadeOut(300);
                    },
                    updateStatus: function(data) {
                        $(document).find(".mfp-figure").stop().fadeOut(300);
                    },
                    imageLoadComplete: function() {
                        $(document).find(".mfp-figure").stop().fadeIn(300);

                        if(ggmp_size_check) {
                            clearTimeout(ggmp_size_check);
                        }
                        ggmp_size_check = setTimeout(function() {
                            var lb_h = $(document).find(".mfp-content").outerHeight();
                            var win_h = $(window).height();

                            if(win_h < lb_h) {
                                var diff = lb_h - win_h; 
                                var img_h = $(document).find(".mfp-img").height() - diff;	

                                $(document).find(".mfp-img").clearQueue().css("max-height", img_h); 
                            }

                            ggmp_size_check = false
                        }, 50);
                    },
                },
                items: sel_img
            });

            var gg_magnificPopup = $.magnificPopup.instance;
            gg_magnificPopup.goTo(clicked_index);';
            break;
    
    
        case 'imagelb' : // imageLightbox
            $code .= "
            const uniqid = new Date().getTime();
            $.each(Object.keys(gall_obj), function(i, v) {
                var obj = gall_obj[v];
                var txt = (obj.descr) ? `<p class='gg_lb_p_margin'><strong>`+ obj.title +`</strong></p>`+ obj.descr : obj.title;

                $('#gg_lb_gall').append(`<a href='`+ obj.img +`' rel='`+ uniqid +`' class='gg_displaynone'><img src='' alt='`+ gg_lb_html_fix(txt) +`' /></a>`);
            });

            var selectorF = '#gg_lb_gall a[rel='+uniqid+']';
            var instanceF = $( selectorF ).imageLightbox({
                //selector:       'a[data-imagelightbox]', // string;
                allowedTypes:   '',
                animationSpeed: ". absint(get_option('gg_lb_time', 400)) .",
                activity:       true,
                arrows:         true,
                button:         true,
                caption:        true,
                fullscreen:     true,
                gutter:         ". (100 - absint(get_option('gg_lb_max_h', 10))) .",
                offsetY:        0,
                navigation:     false,
                overlay:        true,
            });

            $('#gg_lb_gall > a:eq('+ clicked_index +')').trigger('click');";
            break;
    
    
        case 'photobox' :  // PHOTOBOX
            $code .= "
            $.each(Object.keys(gall_obj), function(i, v) {
                var obj = gall_obj[v];
                var txt = (obj.descr) ? obj.title+' - '+obj.descr : obj.title;

                $('#gg_lb_gall').append(`<a href='`+ obj.img +`'><img src='`+ gg_lb_thumb(obj.img) +`' title='`+ txt +`' /></a>`);
            });

            if(gg_ptb_executed) {
                $('#gg_lb_gall').photobox('destroy');
            }
            gg_ptb_executed = true;

            $('#gg_lb_gall').photobox('a',{ 
                time: ". absint(get_option('gg_lb_ss_time', 4000)) .",
                history: false,
                loop: true,
                rotatable: false,
                zoomable: ". ((!get_option('gg_photobox_zoom')) ? 'false' : 'true') .", 
                thumbs: ". ((!get_option('gg_lb_thumbs')) ? 'false' : 'true') .", 
                autoplay: ". ((!get_option('gg_lb_slideshow')) ? 'false' : 'true') ." 
            });

            $('#gg_lb_gall a:eq('+ clicked_index +')').trigger('mouseenter.photobox');
            $('#gg_lb_gall a:eq('+ clicked_index +')').trigger('click');";
            break;	
            
            
        endswitch;
    $code .= "
    };";
        
    return $code;                                        
}

