let wpc_vars = {
    api_url: 'https://images.classix.se/', quality: 'intelligent', webp_enabled: '1', retina_enabled: '1', exif_enabled: 'true', excluded_list: '', adaptive_enabled: 'true'
};

if (wpc_vars.excluded_list !== '') {
    var excludedList = wpc_vars.excluded_list;
    excludedList = excludedList.split(',');
} else {
    var excludedList = '';
}

const PureJs = function (api_url, quality, retina, webp, exif, adaptive) {
    if (typeof api_url !== 'undefined' && api_url !== '' && api_url !== null) {
        wpc_vars.api_url = api_url;
    }
    if (typeof quality !== 'undefined' && quality !== '' && quality !== null) {
        wpc_vars.quality = quality;
    }
    if (typeof webp !== 'undefined' && webp !== '' && webp !== null) {
        wpc_vars.webp_enabled = webp;
    }
    if (typeof retina !== 'undefined' && retina !== '' && retina !== null) {
        wpc_vars.retina_enabled = retina;
    }
    if (typeof exif !== 'undefined' && exif !== '' && exif !== null) {
        wpc_vars.exif_enabled = exif;
    }
    if (typeof adaptive !== 'undefined' && adaptive !== '' && adaptive !== null) {
        wpc_vars.adaptive_enabled = adaptive;
    }

    // Setting event handlers through constructor
    window.addEventListener("resize", lazyLoad);
    window.addEventListener("orientationchange", lazyLoad);
    document.addEventListener("scroll", lazyLoad);
    document.addEventListener("DOMContentLoaded", load);
}

let lazyImages = [];
let pictureTag = [];
let API_URL_FULL;
let API_URL_FULL_SVG;
let browserWidth;
let forceWidth = 0;
let isSvg = false;
let imageIsLogo = false;
let isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
if (isSafari) {
    wpc_vars.webp_enabled = 'false';
}

function load() {
    API_URL_FULL = wpc_vars.api_url + 'q:' + wpc_vars.quality + '/retina:' + wpc_vars.retina_enabled + '/webp:' + wpc_vars.webp_enabled + '/w:1/url:';
    API_URL_FULL_SVG = wpc_vars.api_url + 'asset:';
    browserWidth = window.innerWidth;
    lazyImages = [].slice.call(document.querySelectorAll("img[data-src]"));
    pictureTag = [].slice.call(document.querySelectorAll("picture"));
    lazyLoad(); // Replace URLs of all lazyload images with <img> tag
    pictureLoad(); // Replace URLs of all images within <picture> tag
}

function pictureLoad() {
    pictureTag.forEach(function (pictureImage) {
        let childrenPictures = pictureImage.children;

        for (let i = 0; i < childrenPictures.length; i++) {
            let childPicture = childrenPictures[i];
            // Check if image has <img> tag, if so, don't manipulate it because new API URL has already been set for it
            if (childPicture.tagName == 'IMG') {
                return;
            }


            checkSvgAndLogo(childPicture);
            let imgWidth = getImageWidth(childPicture);
            setNewApiURL(childPicture, imgWidth);
        }
    });
}

function lazyLoad() {
    lazyImages.forEach(function (lazyImage) {

        if (lazyImage == 'undefined') {
            console.log('LazyImage undefined 85');
            return;
        }


        if (lazyImage.src !== 'undefined') {
            if (lazyImage.src.startsWith('//')) {
                lazyImage.src = 'https:' + lazyImage.src;
            }
        }

        if (lazyImage.hasAttribute('data-src')) {
            dataSrc = lazyImage.getAttribute('data-src');
            if (dataSrc.startsWith('//')) {
                lazyImage.setAttribute('data-src','https:'+dataSrc);
            }
        }

        if (checkExcluded(lazyImage)) {
            console.log('LazyImage excluded 85');
            return;
        }

        checkSvgAndLogo(lazyImage);
        let imgWidth = getImageWidth(lazyImage);
        setNewApiURL(lazyImage, imgWidth);

        lazyImage.style.opacity = 0;
        lazyImage.classList.add("lazy");
        lazyImage.classList.add("ic-fade-in");
        lazyImage.classList.remove("wps-ic-lazy-image");
        lazyImage.style.opacity = null;

        lazyImages = lazyImages.filter(function (image) {
            return image !== lazyImage;
        });
    });
}

function setNewApiURL(image, imgWidth) {
    let newApiURL;

    if (typeof image.dataset.srcset !== 'undefined' && image.dataset.srcset != '') {
        image.dataset.srcset = getSrcset(image.dataset.srcset.split(",")); // Srcset links and widths as array
    }
    else if (typeof image.srcset !== 'undefined' && image.srcset != '') {
        image.srcset = getSrcset(image.srcset.split(",")); // Srcset links and widths as array
    }

    if (typeof image.dataset.src !== 'undefined' && image.dataset.src != '') {
        if (isSvg) {
            newApiURL = API_URL_FULL_SVG + image.dataset.src;
        }
        else {
            newApiURL = API_URL_FULL + image.dataset.src;
            newApiURL = newApiURL.replace(/w:(\d{1,5})/g, 'w:' + imgWidth);
        }
        imageIsLogo = false;
        isSvg = false;
        image.dataset.src = getNewApiURL(newApiURL);
    }
    else if (typeof image.src !== 'undefined' && image.src != '') {
        if (isSvg) {
            newApiURL = API_URL_FULL_SVG + image.src;
        }
        else {
            newApiURL = API_URL_FULL + image.src;
            newApiURL = newApiURL.replace(/w:(\d{1,5})/g, 'w:' + imgWidth);
        }
        imageIsLogo = false;
        isSvg = false;
        image.src = getNewApiURL(newApiURL);
    }
}

function getNewApiURL(newApiURL) {
    if (window.devicePixelRatio >= 2 && wpc_vars.retina_enabled == 'true') {
        newApiURL = newApiURL.replace(/retina:false/g, 'retina:true');
    }
    else {
        newApiURL = newApiURL.replace(/retina:true/g, 'retina:false');
    }

    if (wpc_vars.webp_enabled == 'true' && isSafari == false) {
        newApiURL = newApiURL.replace(/webp:false/g, 'webp:true');
    }
    else {
        newApiURL = newApiURL.replace(/webp:true/g, 'webp:false');
    }

    if (wpc_vars.exif_enabled == 'true') {
        newApiURL = newApiURL.replace(/exif:false/g, 'exif:true');
    }
    else {
        newApiURL = newApiURL.replace(/\/exif:true/g, '');
        newApiURL = newApiURL.replace(/\/exif:false/g, '');
    }
    return newApiURL;
}

function getParents(elem) {
    let parents = [];
    // Push each parent element to the array
    for (; elem && elem !== document; elem = elem.parentNode) {
        if (elem.childElementCount > 1) {
            break;
        }
        else {
            if (elem.classList.contains('logo')) {
                return 'logo';
                break;
            }
            parents.push(elem);
        }
    }
    return parents;
}

function getParentWidth(parents) {
    let parent_width = 1;
    //Get last parent key from array and extract its values
    let last = Object.keys(parents)[parents.length - 1];
    let parent = Object.values(parents)[last];
    let parent_style = window.getComputedStyle(parent);
    let widthIsPercent = parent_style.width.indexOf("%") > -1;

    if (!widthIsPercent) {
        parent_width = Math.round(parseInt(parent_style.width));
    }

    return parent_width;
}


/**
 * Figures out the width of an image from srcset url
 * https://wpcompresscomfa428.zapwp.com/q:lossless/retina:false/webp:false/w:1/url:{IMAGE} 814w
 *
 * 814w is width of the srcset element, that needs to be set instead of w:1, but ONLY if that parameter
 * has "w" in it.. if it's anything like "2x" or "1x" .. ignore, leave w:1
 * @param srcSetUrl
 */
function srcSetUpdateWidth(srcSetUrl) {
    let srcSetWidth = srcSetUrl.split(' ').pop();
    if (srcSetWidth.endsWith('w')) {
        // Remove w from width string
        let Width = srcSetWidth.slice(0, -1);
        srcSetUrl = srcSetUrl.replace(/w:(\d{1,5})/g, 'w:' + Width);
    }
    return srcSetUrl;
}

function getSrcset(sourceArray) {
    let changedSrcset = '';
    sourceArray.forEach(function (imageSource) {

        let newApiURL = API_URL_FULL + imageSource.trimStart();
        let imageExtension = imageSource.split('.').pop();
        if (imageExtension.includes('svg')) {
            newApiURL = API_URL_FULL_SVG + imageSource.trimStart();
        }
        else {
            newApiURL = getNewApiURL(newApiURL);
        }

        newApiURL = srcSetUpdateWidth(newApiURL);

        changedSrcset += newApiURL + ",";
    });

    return changedSrcset.slice(0, -1); // Remove last comma
}

function getImageWidth(image) {
    // We need to store old img.src so that we can return it to <img> once we are done with SVG
    let oldImgSrc = image.src;

    // Setting image source to be SVG width, so that we can get a proper size of the parent container in case the image container is 1x1, temporary workaround
    image.src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMCI+PHBhdGggZD0iTTIgMmgxMDAwdjEwMEgyeiIgZmlsbD0iI2ZmZiIgb3BhY2l0eT0iMCIvPjwvc3ZnPg==";


    let parentHeight;
    let imgWidth;
    let imageParentType;
    let imageParent;
    let parentStyle;
    let image_parents = getParents(image);
    let imageStyle = window.getComputedStyle(image);
    let ImageWidthPreloaded = Math.round(parseInt(imageStyle.width));
    let parentWidth = getParentWidth(image_parents);
    let imageWidth = ImageWidthPreloaded;
    let imageWidthNatural = image.dataset.width;
    let imageHeightNatural = image.dataset.height;


    if (!imageIsLogo) {
        // Image is not a logo
        if (wpc_vars.adaptive_enabled == '1' || wpc_vars.adaptive_enabled == 'true') {
            if (!imageWidth || imageWidth == 0 || typeof imageWidth == 'undefined') {

                // Fix for forcing image width to maximum
                let imageOldWidth = image.style.width;
                image.style.width = '9999px';

                imageParentType = image.parentNode.nodeName.toLowerCase();
                imageParent = image.parentNode;

                if (imageParentType == 'a') {
                    imageParent = image.parentNode.parentElement;
                }

                parentStyle = window.getComputedStyle(imageParent);

                if (parentStyle.width == 'auto') {
                    imageParent = imageParent.parentNode;
                    parentStyle = window.getComputedStyle(imageParent);
                }

                parentWidth = Math.round(parseInt(parentStyle.width));
                imgWidth = Math.round(parseInt(parentStyle.width));

                if (imgWidth == parentWidth) {
                    imageParent = imageParent.parentNode;
                    parentStyle = window.getComputedStyle(imageParent);
                    parentWidth = Math.round(parseInt(parentStyle.width));
                }
                if (typeof imgWidth == 'undefined' || !imgWidth || imgWidth == 0 || isNaN(imgWidth)) {
                    imgWidth = 1;
                }

                // Return image width to default
                image.style.width = imageOldWidth;
            }
            else {
                imgWidth = Math.round(parseInt(imageWidth));

                imageParentType = image.parentNode.nodeName.toLowerCase();
                imageParent = image.parentNode;

                if (imageParentType == 'a') {
                    imageParent = image.parentNode.parentElement;
                }

                parentStyle = window.getComputedStyle(imageParent);
                parentWidth = Math.round(parseInt(parentStyle.width));
                parentHeight = Math.round(parseInt(parentStyle.height));

                if (isNaN(parentWidth) || imgWidth == parentWidth) {
                    imageParent = imageParent.parentNode;
                    parentStyle = window.getComputedStyle(imageParent);
                    parentWidth = Math.round(parseInt(parentStyle.width));
                    parentHeight = Math.round(parseInt(parentStyle.height));
                }

                if (isNaN(imgWidth) || isNaN(parentWidth) || imgWidth > browserWidth) {
                    imgWidth = browserWidth;
                }
            }
        }
        else {
            imgWidth = Math.round(parseInt(window.getComputedStyle(image).width));

            imageParent = image.parentNode;
            parentStyle = window.getComputedStyle(imageParent);
            parentWidth = Math.round(parseInt(parentStyle.width));
            parentHeight = Math.round(parseInt(parentStyle.height));
        }
    }
    else {
        // Image is a logo or something like a logo
        if (wpc_vars.adaptive_enabled == '1' || wpc_vars.adaptive_enabled == 'true') {
            imgWidth = 400;
        }
        else {
            imgWidth = 1;
        }
        imageParent = image.parentNode;
        parentStyle = window.getComputedStyle(imageParent);
        parentWidth = Math.round(parseInt(parentStyle.width));
        parentHeight = Math.round(parseInt(parentStyle.height));
    }

    if (imgWidth > browserWidth) {
        imgWidth = browserWidth;
    }

    let imageRatio = imageWidthNatural / imageHeightNatural;

    if (typeof parentHeight == 'undefined' || !parentHeight || parentHeight == 0) {
        parentHeight = image.dataset.height;
    }
    if (imageRatio < 1) {
        imgWidth = Math.round((parentHeight * imageRatio));
    }
    if (typeof imgWidth == 'undefined' || imageIsLogo && (imgWidth < 200 || (!imgWidth || imgWidth == 0))) {
        imgWidth = 200;
    }
    if (forceWidth > 0 && imgWidth > 320) {
        imgWidth = forceWidth;
    }
    if (typeof imgWidth == 'undefined' || !imgWidth || imgWidth == 0 || isNaN(imgWidth) || imgWidth <= 30) {
        imgWidth = 1;
    }

    // Restore odl image source
    image.src = oldImgSrc;

    return imgWidth;
}

function getImageFilename(image) {
    let imageFilename;
    if (typeof image.dataset.src !== 'undefined' && image.dataset.src != '') {
        if (image.dataset.src.endsWith('url:https')) {
            return false;
        }
        imageFilename = image.dataset.src;
    }
    else if (typeof image.src !== 'undefined' && image.src != '') {
        if (image.src.endsWith('url:https')) {
            return false;
        }
        imageFilename = image.src;
    }
    return imageFilename;
}



function checkExcluded(image) {
    let imageFilename = getImageFilename(image);

    if (!imageFilename) {
        console.log('No filename ' + imageFilename);
        return true;
    }

    if (typeof imageFilename !== 'undefined' && imageFilename !== '') {
        if (excludedList !== '') {
            for (let excludedImage of excludedList) {
                if (image.src.includes(excludedImage)) {
                    return true;
                }
            }

        }
    }
}


function checkSvgAndLogo(image) {
    let imageFilename = getImageFilename(image);

    if (!imageFilename) {
        return true;
    }

    if (typeof imageFilename !== 'undefined' && imageFilename !== '') {
        let imageExtension = imageFilename.split('.').pop();
        // Image filename, extension and isLogo is checked only for data-src and src images because srcset images have set width and svg internal check
        if (imageExtension !== 'jpg' && imageExtension !== 'jpeg' && imageExtension !== 'gif' && imageExtension !== 'png' && imageExtension !== 'svg' && image.src.includes('svg+xml') == false && image.src.includes('placeholder.svg') == false) {
            return;
        }
        if (imageExtension == 'svg') {
            isSvg = true;
        }
    }

    let imageClass = [].slice.call(image.classList);
    imageClass = imageClass.join(" ");
    if (typeof imageClass !== 'undefined' && imageClass !== '') {
        if (imageClass.toLowerCase().includes("logo") || imageFilename.toLowerCase().includes("logo")) {
            imageIsLogo = true;
        }
    }
}

// Setting event handlers in main program
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
document.addEventListener("scroll", lazyLoad);
document.addEventListener("DOMContentLoaded", load);