/**
 * @author WebRotate 360 LLC
 * @copyright Copyright (C) 2023 WebRotate 360 LLC. All rights reserved.
 * @license GNU General Public License version 2 or later (http://www.gnu.org/copyleft/gpl.html).
 * @version 4.0
 * @module WebRotate 360 Product Viewer for Prestashop.
*/

jQuery(document).ready(function() {
    if (typeof __webrotate360  === 'undefined')
        return;

    if (__webrotate360.is_viewer_popup) {
        WR360InitPopupViewer(__webrotate360);
        return;
    }

    WR360InitEmbeddedViewer(__webrotate360);
});

function WR360InitEmbeddedViewer(cfg) {
    var imageDiv = jQuery(cfg.placeholder);
    if (!imageDiv.length)
        return;

    var viewerApi = null,
        lastViewerXml = cfg.config_file_url;

    function hook360Thumb() {
        var imgClass = '.images-container ul.product-images img',
            selectedClass = 'js-thumb-selected selected',
            $thumbs = jQuery(imgClass),
            $firstThumb = jQuery($thumbs[0]),
            thumbImgWidth = $firstThumb.attr('width'),
            thumbImgHeight = $firstThumb.attr('height'),
            firstThumbAlt =  $firstThumb.attr('alt'),
            $thumbParent = jQuery('.images-container ul.product-images'),
            $viewer = jQuery('#wr360PlayerId');

        if (firstThumbAlt && firstThumbAlt.indexOf('.xml') > 0 && firstThumbAlt !== lastViewerXml) {
            lastViewerXml = firstThumbAlt;
            $firstThumb.attr('title', '');
        }
        else if (lastViewerXml !== cfg.config_file_url)
            lastViewerXml = cfg.config_file_url;

        if (cfg.gallery_order === 'first') {
            $viewer.css({
                visibility: 'visible',
                'z-index': 1
            });

            $thumbs.removeClass(selectedClass);
            $thumbParent.prepend("<li class='thumb-container js-thumb-container'><img class='thumb js-thumb js-thumb-selected selected thumb360' alt='' src='" +
                cfg.popup_thumb + "' width='" + thumbImgWidth + "' height='" + thumbImgHeight + "'/></li>");
        }
        else {
            $thumbParent.append("<li class='thumb-container js-thumb-container'><img class='thumb js-thumb thumb360' alt='360' src='" +
                cfg.popup_thumb + "' width='" + thumbImgWidth + "' height='" + thumbImgHeight + "'/></li>");
        }

        jQuery(imgClass).click(function() {
            $thumbs.removeClass(selectedClass);
            jQuery(this).addClass(selectedClass);
            var is360 = jQuery(this).hasClass('thumb360');
            $viewer.css({
                visibility: is360 ? 'visible' : 'hidden',
                'z-index': is360 ? 1 : -1
            });
        });
    }

    imageDiv = jQuery(imageDiv[0]);
    var isGalleryOn = cfg.placeholder.indexOf('.product-cover') >= 0;
    if (isGalleryOn) {
        imageDiv.append("<div id='wr360PlayerId' style='position:absolute;width:100%;height:100%;left:0;top:0;z-index:-1;visibility:hidden;'></div>");
        hook360Thumb();
    }
    else {
        if (cfg.viewer_width.length > 0)
            imageDiv.css({ width: cfg.viewer_width });
        if (cfg.viewer_height.length > 0)
            imageDiv.css({ height: cfg.viewer_height });
        imageDiv.append("<div id='wr360PlayerId'></div>");
    }

    var rotator = WR360.ImageRotator.Create('wr360PlayerId');

    rotator.settings.graphicsPath        = cfg.graphics_path;
    rotator.settings.configFileURL       = lastViewerXml;
    rotator.settings.rootPath            = cfg.root_path;
    rotator.settings.responsiveBaseWidth = isGalleryOn ? 0 : parseInt(cfg.base_width);
    rotator.settings.responsiveMinHeight = isGalleryOn ? 0 : parseInt(cfg.min_height);
    rotator.settings.googleEventTracking = cfg.use_analytics === 'true';
    rotator.licenseFileURL               = cfg.license_path;

    rotator.settings.apiReadyCallback = function(api, isFullScreen) {
        if (!isFullScreen)
            viewerApi = api;
        if (cfg.api_callback.length > 0) {
            var fn = window[cfg.api_callback];
            if (typeof fn === 'function')
                fn(api, isFullScreen);
        }
    };

    rotator.runImageRotator();

    if (!isGalleryOn)
        return;

    var savedReplaceWith = jQuery.fn.replaceWith;

    jQuery.fn.replaceWith = function() {
        var refreshElementClass = 'images-container',
            $viewer = null;

        if (jQuery(this).hasClass(refreshElementClass)) {
            $viewer = jQuery('#wr360PlayerId').detach();
            $viewer.css({ visibility: 'hidden' });
        }

        savedReplaceWith.apply(this, arguments);

        if ($viewer) {
            imageDiv = jQuery(cfg.placeholder);
            if (imageDiv.length > 0) {
                $viewer.appendTo(imageDiv[0]);
                hook360Thumb();
                if (viewerApi)
                    viewerApi.reload(lastViewerXml, cfg.root_path);
            }
        }
    };
}

function WR360InitPopupViewer(cfg) {
    var popupElm = jQuery(cfg.placeholder);
    if (popupElm.length <= 0)
        return;

    popupElm.html("<a href='"
        + cfg.popup_href
        + "'"
        + "data-rel='prettyPhoto'><img src='"
        + cfg.popup_thumb
        + "'/></a>");

    jQuery("a[data-rel^='prettyPhoto']").prettyPhoto({
        animation_speed: 0,
        deeplinking: false,
        theme: cfg.popup_skin
    });

    popupElm.css({ visibility: 'visible' });
}