var ajaxUrl = 'https://tracking.carvid360.com/lithiachryslermissoula.com/';var colorSceheme = '#c3002f';var fontColorSceheme = '#ffffff';var CarVideos = null; window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-E3BSMW0TZM');

// CarVid360 VDP Integration for Dealer.com v9 Template
(function() {
    'use strict';

    var carvidInitialized = false;
    var carvidDebug = true; // Set to false in production for verbose logging

    // Basic log - always shows (initialization, loaded, errors)
    function log(message, data) {
        if (data !== undefined) {
            console.log('CARVID VDP -', message, data);
        } else {
            console.log('CARVID VDP -', message);
        }
    }

    // Debug log - only shows when carvidDebug is true
    function debugLog(message, data) {
        if (carvidDebug) {
            if (data !== undefined) {
                console.log('CARVID VDP [DEBUG] -', message, data);
            } else {
                console.log('CARVID VDP [DEBUG] -', message);
            }
        }
    }

    // Ensure jQuery is loaded
    function ensureJQuery(callback) {
        if (typeof jQuery !== 'undefined') {
            debugLog('jQuery is loaded');
            callback();
        } else {
            debugLog('jQuery is not loaded, loading it now...');
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'https://code.jquery.com/jquery-3.6.0.min.js';
            script.onload = function() {
                debugLog('jQuery loaded successfully');
                callback();
            };
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    }

    // Get VIN from the page
    function getVIN() {
        // Try hidden input field first
        var vinInput = document.querySelector('input[name="vin"]');
        if (vinInput && vinInput.value) {
            return vinInput.value;
        }

        // Try DDC.dataLayer
        if (typeof DDC !== 'undefined' && DDC.dataLayer && DDC.dataLayer.vehicles && DDC.dataLayer.vehicles[0]) {
            return DDC.dataLayer.vehicles[0].vin;
        }

        return null;
    }

    // Get vehicle metadata from DDC.dataLayer
    function getVehicleMeta() {
        if (typeof DDC === 'undefined' || !DDC.dataLayer || !DDC.dataLayer.vehicles || !DDC.dataLayer.vehicles[0]) {
            return null;
        }

        var vehicle = DDC.dataLayer.vehicles[0];

        // Helper function to safely get and clean price values
        function cleanPrice(value) {
            if (!value || value === '0') return null;
            return String(value).replace(/[$,]/g, '');
        }

        return {
            stock_no: vehicle.stockNumber ? vehicle.stockNumber.replace('&', '%26') : '',
            stock_status: vehicle.status || '',
            msrp: cleanPrice(vehicle.msrp),
            retailValue: cleanPrice(vehicle.retailValue),
            internet_price: cleanPrice(vehicle.salePrice),
            asking_price: cleanPrice(vehicle.askingPrice),
            year: vehicle.year || vehicle.modelYear || '',
            make: vehicle.make ? vehicle.make.replace('&', '%26') : '',
            model: vehicle.model ? vehicle.model.replace('&', '%26') : '',
            trim: vehicle.trim || '',
            body: vehicle.bodyStyle || '',
            engine: vehicle.engine ? vehicle.engine.replace('&', '%26') : '',
            transmission: vehicle.transmission ? vehicle.transmission.replace('&', '%26') : '',
            color: vehicle.color || vehicle.exteriorColor || '',
            interior_color: vehicle.interiorColor || '',
            type: vehicle.inventoryType || '',
            link: vehicle.link || '',
            driveLine: vehicle.driveLine || '',
            engineSize: vehicle.engineSize || '',
            fuelType: vehicle.fuelType || '',
            odometer: vehicle.odometer || '',
            images: vehicle.images || ''
        };
    }

    // Build VIN map from CarVideos array
    function buildVinMap() {
        var VINMap = {};
        if (typeof CarVideos !== 'undefined' && CarVideos !== null && Array.isArray(CarVideos)) {
            for (var i = 0; i < CarVideos.length; i++) {
                VINMap[CarVideos[i].VIN] = CarVideos[i].video;
            }
            debugLog('VIN Map built with', Object.keys(VINMap).length + ' videos');
        }
        return VINMap;
    }

    // Check if a VIN has a video
    function hasVideo(VINMap, vin) {
        return VINMap[vin] || null;
    }

    // Send tracking data to CarVid360 server
    function sendTrackingData(vin, meta) {
        if (typeof ajaxUrl === 'undefined') {
            debugLog('ajaxUrl not defined, skipping tracking');
            return;
        }

        var encodedMeta = encodeURIComponent(JSON.stringify(meta));

        $.ajax({
            type: 'GET',
            url: ajaxUrl + 'tracking.php?VIN=' + vin + '&meta=' + encodedMeta,
            success: function(response) {
                debugLog('Vehicle info sent to CarVid360:', response);
            },
            error: function(xhr, status, error) {
                log('Vehicle info failed to send:', error);
            }
        });
    }

    // Create video embed HTML
    function createVideoEmbed(videoId) {
        return '<div class="carvid-video-container" style="position:relative; width:100%; aspect-ratio:4/3;">' +
            '<div class="carvid-video-title" style="width:100%; background:#0d65bf; color:#fff; font-size:14px; text-align:center; padding:8px 5px; position:absolute; z-index:100; top:0;">' +
            'Check out the 360&deg; Walkaround Video</div>' +
            '<iframe src="https://www.youtube.com/embed/' + videoId + '?rel=0&showinfo=0&playlist=' + videoId + '&loop=1&autoplay=1&mute=1" ' +
            'style="position:absolute; top:0; left:0; width:100%; height:100%;" ' +
            'frameborder="0" allowfullscreen="allowfullscreen" ' +
            'mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" ' +
            'oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen"></iframe>' +
            '</div>';
    }

    // Scroll thumbnail strip to show the video thumbnail
    function scrollToVideoThumbnail() {
        var $thumbnailSlider = $('.thumbnail-wrapper .slick-slider');
        if ($thumbnailSlider.length && $thumbnailSlider.slick) {
            // Use slick's goTo method to scroll to first slide (video thumbnail)
            try {
                $thumbnailSlider.slick('slickGoTo', 0);
                debugLog('Scrolled thumbnail slider to video thumbnail');
            } catch (e) {
                debugLog('slickGoTo failed, trying manual scroll');
                // Fallback: manually scroll the track
                var $track = $('.thumbnail-wrapper .slick-track');
                if ($track.length) {
                    $track.css('transform', 'translate3d(0px, 0px, 0px)');
                }
            }
        } else {
            // Fallback for non-slick slider
            var $track = $('.thumbnail-wrapper .slick-track');
            if ($track.length) {
                $track.css('transform', 'translate3d(0px, 0px, 0px)');
                debugLog('Reset thumbnail track position');
            }
        }
    }

    // Add video tab to the modal gallery menu
    function addVideoTabToModal(videoId) {
        var $menuContainer = $('.modal-content-gallery-menu .d-flex');
        if ($menuContainer.length === 0) {
            debugLog('Modal gallery menu not found');
            return false;
        }

        // Check if we already added the video tab
        if ($menuContainer.find('.carvid-video-tab').length > 0) {
            debugLog('Video tab already exists');
            return true;
        }

        // Create the video tab button (matching the Photos button structure)
        var $videoTab = $('<div class="mb-md-5 mr-5 mr-md-0 carvid-video-tab">' +
            '<button type="button" data-testid="video-gallery-button" class="gallery-button border-left-0 border-top-0 border-right-0 w-60 mx-0 bg-transparent text-body p-0 d-flex align-items-center">' +
            '<i data-testid="text-icon" aria-hidden="true" class="ddc-icon ddc-icon-play3 mr-3" role="presentation" tabindex="-1"></i>' +
            '<span class="ddc-font-size-xsmall font-weight-bold">Video</span>' +
            '</button></div>');

        // Get the Photos tab button
        var $photosTab = $menuContainer.find('[data-testid="gallery-button"]').closest('div');

        // Add click handlers for tab switching
        $videoTab.find('button').on('click', function(e) {
            e.preventDefault();
            showModalVideo(videoId);
            // Update active states
            $menuContainer.find('.gallery-button').removeClass('gallery-button--active');
            $(this).addClass('gallery-button--active');
            // Add active state to video thumbnail, remove from others
            $('.thumbnail-wrapper .slider-thumbnail').removeClass('active');
            $('.carvid-video-thumb .slider-thumbnail').addClass('active');
            // Scroll thumbnail strip to show video thumbnail (first position)
            scrollToVideoThumbnail();
        });

        $photosTab.find('button').on('click', function() {
            // Update active states when Photos is clicked
            $menuContainer.find('.gallery-button').removeClass('gallery-button--active');
            $(this).addClass('gallery-button--active');
            hideModalVideo();
        });

        // Add click handler to thumbnails - clicking a thumbnail switches back to Photos
        $('.thumbnail-wrapper').on('click', 'button:not(.carvid-video-thumb)', function() {
            debugLog('Thumbnail clicked, switching to Photos');
            // Update active states
            $menuContainer.find('.gallery-button').removeClass('gallery-button--active');
            $photosTab.find('button').addClass('gallery-button--active');
            // Remove active state from video thumbnail (site handles active state on other thumbs)
            $('.carvid-video-thumb .slider-thumbnail').removeClass('active');
            hideModalVideo();
        });

        // Add video thumbnail to the beginning of the thumbnail strip
        addVideoThumbnail($videoTab.find('button'));

        // Insert video tab before the Photos tab
        $photosTab.before($videoTab);
        debugLog('Added 360 Video tab to modal');

        return true;
    }

    // Add video thumbnail with play icon to the thumbnail strip
    function addVideoThumbnail($videoTabButton) {
        var $thumbnailWrapper = $('.thumbnail-wrapper .slick-track');
        if ($thumbnailWrapper.length === 0) {
            debugLog('Thumbnail wrapper not found');
            return;
        }

        // Check if we already added the video thumbnail
        if ($thumbnailWrapper.find('.carvid-video-thumb').length > 0) {
            debugLog('Video thumbnail already exists');
            return;
        }

        // Get the first image to use as the video thumbnail background
        var firstImageSrc = $thumbnailWrapper.find('img').first().attr('src');
        if (!firstImageSrc) {
            debugLog('No image found for video thumbnail');
            return;
        }

        // Create video thumbnail with play icon overlay
        // Using native .active class on .slider-thumbnail for consistent styling
        var $videoThumb = $('<div class="slick-slide carvid-video-thumb-wrapper" data-index="-1" style="width: 161px;">' +
            '<div>' +
            '<button type="button" class="btn-unstyled mb-sm-4 carvid-video-thumb" style="width: 100%; display: inline-block; position: relative;">' +
            '<div class="thumbnail-img-wrapper" role="tab" aria-label="360 Video" tabindex="-1">' +
            '<img alt="360 Video thumbnail" src="' + firstImageSrc + '" class="slider-thumbnail active w-100 slider-thumbnail--desktop">' +
            '<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 40px; height: 40px; background: #0d66bfd3;; border-radius: 50%; display: flex; align-items: center; justify-content: center;">' +
            '<i class="ddc-icon ddc-icon-play3" style="color: white; font-size: 18px; margin-left: 3px;"></i>' +
            '</div>' +
            '</div>' +
            '</button>' +
            '</div>' +
            '</div>');

        // Add click handler to switch to video
        $videoThumb.find('button').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            debugLog('Video thumbnail clicked, switching to Video');
            // Trigger the video tab click (this handles active state updates)
            $videoTabButton.click();
        });

        // Prepend to the beginning of the thumbnail strip
        $thumbnailWrapper.prepend($videoThumb);
        debugLog('Added video thumbnail to strip');
    }

    // Show video in the modal (replacing the photo carousel)
    function showModalVideo(videoId) {
        var $sliderContainer = $('.modal-content-gallery-slider');
        if ($sliderContainer.length === 0) {
            debugLog('Modal slider container not found');
            return;
        }

        // Hide the photo slider and thumbnails
        $sliderContainer.find('.slider-container').hide();
        $sliderContainer.find('.thumbnail-wrapper').hide();

        // Check if video container already exists
        var $videoContainer = $sliderContainer.find('.carvid-modal-video');
        if ($videoContainer.length === 0) {
            // Create video container for modal - match the slider dimensions
            var videoHtml = '<div class="carvid-modal-video" style="width:100%; display:flex; align-items:center; justify-content:center; padding: 0 40px;">' +
                '<div style="width:100%; max-width:900px; aspect-ratio:16/9;">' +
                '<iframe src="https://www.youtube.com/embed/' + videoId + '?rel=0&showinfo=0&playlist=' + videoId + '&loop=1&autoplay=1&mute=0" ' +
                'style="width:100%; height:100%;" ' +
                'frameborder="0" allowfullscreen="allowfullscreen" ' +
                'mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" ' +
                'oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen"></iframe>' +
                '</div></div>';
            $sliderContainer.prepend(videoHtml);
            debugLog('Created modal video container');
        } else {
            $videoContainer.show();
        }

        debugLog('Showing modal video');
    }

    // Hide video and show photos in modal
    function hideModalVideo() {
        var $sliderContainer = $('.modal-content-gallery-slider');
        if ($sliderContainer.length === 0) return;

        // Show the photo slider and thumbnails
        $sliderContainer.find('.slider-container').show();
        $sliderContainer.find('.thumbnail-wrapper').show();

        // Hide the video container
        var $videoContainer = $sliderContainer.find('.carvid-modal-video');
        $videoContainer.hide();

        debugLog('Hiding modal video, showing photos');
    }

    // Replace gallery main image with video
    function replaceGalleryWithVideo(videoId) {
        var $gallery = $('.ws-vehicle-gallery');
        if ($gallery.length === 0) {
            debugLog('Gallery not found');
            return false;
        }

        var $leftColumn = $gallery.find('.left-column');
        if ($leftColumn.length === 0) {
            debugLog('Gallery left column not found');
            return false;
        }

        // Replace the main image area with video embed
        var videoHtml = createVideoEmbed(videoId);
        $leftColumn.html(videoHtml);
        debugLog('Replaced main image with video');

        // Hide the "X Photos" badge
        var $photosBadge = $gallery.find('[data-testid="vertical-toolbar"], .vehicle-gallery-toolbar');
        if ($photosBadge.length) {
            $photosBadge.hide();
            debugLog('Hidden photos badge');
        }

        return true;
    }

    // Watch for modal to open and add video tab
    function setupModalObserver(videoId) {
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.addedNodes.length > 0) {
                    mutation.addedNodes.forEach(function(node) {
                        if (node.nodeType === 1) {
                            // Check if a modal was added
                            var $node = $(node);
                            var $modal = $node.hasClass('modal') ? $node : $node.find('.modal');
                            if ($modal.length > 0) {
                                debugLog('Modal detected, adding video tab...');
                                // Small delay to let modal fully render
                                setTimeout(function() {
                                    addVideoTabToModal(videoId);
                                }, 100);
                            }
                        }
                    });
                }
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });

        debugLog('Modal observer set up');
    }

    // Main function to process the VDP
    function processVDP() {
        var vin = getVIN();
        if (!vin) {
            debugLog('No VIN found on page');
            return;
        }

        debugLog('Processing VDP for VIN:', vin);

        var meta = getVehicleMeta();
        var VINMap = buildVinMap();

        // Check if this vehicle has a video
        var videoId = hasVideo(VINMap, vin);

        if (videoId) {
            debugLog('Video found:', videoId);

            // Try to replace gallery with video
            var replaced = replaceGalleryWithVideo(videoId);

            if (replaced) {
                log('Video embedded successfully for VIN:', vin);
                // Set up observer to add video tab when modal opens
                setupModalObserver(videoId);
            } else {
                debugLog('Could not replace gallery, will retry...');
                return false; // Signal to retry
            }
        } else {
            debugLog('No video found for VIN:', vin);
        }

        // Send tracking data regardless of video
        if (meta) {
            sendTrackingData(vin, meta);
        }

        return true; // Signal success
    }

    // Initialize with retry logic
    function initWithRetry(retryCount) {
        retryCount = retryCount || 0;

        if (retryCount >= 20) {
            log('Max retries reached, stopping');
            return;
        }

        var success = processVDP();

        if (!success && retryCount < 20) {
            debugLog('Retrying in 500ms... (attempt ' + (retryCount + 1) + ')');
            setTimeout(function() {
                initWithRetry(retryCount + 1);
            }, 500);
        }
    }

    // Main initialization
    function init() {
        if (carvidInitialized) {
            debugLog('Already initialized, skipping');
            return;
        }
        carvidInitialized = true;

        log('CarVid360 VDP Script Loading...');

        ensureJQuery(function() {
            // Wait for page to be ready, then start processing
            setTimeout(function() {
                log('Initializing CarVid360 VDP...');
                initWithRetry();
                log('CarVid360 VDP Script Loaded');
            }, 2000);
        });
    }

    // Start initialization based on document ready state
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    // Also run on window load as a fallback
    window.addEventListener('load', function() {
        if (!carvidInitialized) {
            init();
        }
    });

    // Expose functions globally for manual triggering if needed
    window.CarVid360VDP = {
        processVDP: processVDP,
        replaceGalleryWithVideo: replaceGalleryWithVideo
    };

})();
