var isIE = (window.ActiveXObject || "ActiveXObject" in window);
var isEDGE = window.navigator.userAgent.indexOf('Edge/') != -1;
var isFF = window.navigator.userAgent.toLowerCase().indexOf('firefox') != -1;
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
var running = false;
var numberOfImages = 1 + Number(googleFonts === true);
var imageSizeMultiplier = Math.min(Math.max(1, window.devicePixelRatio || (isMobile ? 1.6 : 1)), (touristic && offersCount > 8 && enlargerEnabled) ? 1.2 : (offersCount > 8 && enlargerEnabled) ? 1.4 : 1.6);

$(window).load(decrease);

var thisBody = document.body || document.documentElement;
var thisStyle = thisBody.style;
var supportTransition = thisBody.style.transition !== undefined || thisStyle.WebkitTransition !== undefined || thisStyle.MozTransition !== undefined || thisStyle.MsTransition !== undefined || thisStyle.OTransition !== undefined;


function showImg(obj) {
	if(obj.w<1|obj.h<1)return;
    displayImage(obj.img, obj.id, obj.w, obj.h, obj.formats, obj.forceDiv, obj.dontFade, obj.dontHide, obj.dontCover, obj.isLogo, obj.forceCover);
}

function getResolution(arr, imgW, imgH, ok) {
    imgW = Math.ceil(imageSizeMultiplier * imgW);
    imgH = Math.ceil(imageSizeMultiplier * imgH);
    var deltaX = 9999;
    var deltaY = 9999;
    var xNr = 0;
    var yNr = 0;
    for (var i = 0; i < arr.length; i++) {
        var wXh = arr[i].split('x');
        if (i === 0) oldWxH = wXh;
        var deltaW = Number(wXh[0]) - imgW;
        var deltaH = Number(wXh[1]) - imgH;
        if (deltaW < deltaX && deltaW >= 0) {
            deltaX = deltaW;
            xNr = i;
        }
        if (deltaH < deltaY && deltaH >= 0) {
            deltaY = deltaH;
            yNr = i;
        }
    }
    var nr = touristic?Math.min(xNr, yNr):Math.max(xNr, yNr);
    wXh = arr[nr].split('x');
    return ok ? nr : {
        newRes: 'w=' + wXh[0] + '&h=' + wXh[1],
        oldRes: 'w=' + oldWxH[0] + '&h=' + oldWxH[1]
    };
}

if (isIE) {
    var ie = (function() {
        var undef,
            v = 3,
            div = document.createElement('div'),
            all = div.getElementsByTagName('i');

        while (
            div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );

        return v > 4 ? v : undef;

    }());
    var wrongIE = ie < 10;
    var ie8 = ie < 9;
    if (ie8) touristic = false;
}

function decrease() {
	numberOfImages--;
	if (numberOfImages <= 0 && !running) {
		run();
		running = true;
	}
}

function fadeInElement(el, t, dont) {
    t = t || 400;
    if (supportTransition && !dont) {
        el.css('opacity', '0').css('display', 'block').css('transition-property', 'opacity').css('transition-duration', ((t - 16) / 1000) + 's');
        setTimeout(function() {
            el.css('opacity', '1');
        }, 16);
        setTimeout(function() {
            el.css('transition-property', 'none').css('transition-duration', '0s')
        }, t)
    } else {
        el.css('display', 'block').css('opacity', '1');
    }
}

function getExtension(str) {
    return str.indexOf('.') != -1 ? str.substring(str.lastIndexOf('.') + 1, str.length) : '';
}

function displayImage(url, id, w, h, formats, forceDiv, dontFade, dontHide, dontCover, isLogo, forceCover) {

    isLogo = isLogo && !forceCover;
    var logoContainer = id.indexOf('logo-canvas') != -1;

    var cover = forceCover || (touristic && !dontCover && !isLogo);

    if ((typeof url) === 'string' && url.charAt(0) === "[") {
        try {
            url = JSON.parse(url);
        } catch (err) {}
    }
    var ok = (typeof url) === 'object';
    if (ok) {
        formats = makeFormats(url);
    }
    if (formats) {
        var res = getResolution(formats.split('[').join('').split(']').join('').split(' ').join('').split(','), w, h, ok);
        if (ok) {
            url = url[res].url;
        } else {
            url = url.replace(res.oldRes, res.newRes);
        }
    }

    var mn = {
        w: 0,
        h: 0
    };
    var m = 0;
    var isSVG = getExtension(url) === 'svg';

    forceDiv = forceDiv || dontUseCanvas || imageSizeMultiplier > 1 || isSVG;


    numberOfImages++;
    var child = $('#' + id);
    var mother = child.parent();

    if (isIE) {
        forceDiv = forceDiv || wrongIE;
        if (ie8) {
            makeDiv(w, h);
            return;
        }
    }

    var canvas = document.getElementById(id);

    var c = forceDiv ? null : canvas.getContext('2d');

    var img = new Image();

    var firstTry = true;

    if (!dontHide) mother.css('display', 'none');

    function makeDiv(imgW, imgH) {
        var _w = imgW + "px";
        var _h = imgH + "px";
        child.remove();
        if (ie8 || ((isEDGE || isIE) && isSVG && !cover)) {
            if (!cover) {
                if (isEDGE || isIE) {
                    mother.html('<img src="' + url + '" class="div-image" id="div-image-' + id + '" onload="decrease()" onerror="if(this.secondTry!=true){this.src = noimg;this.secondTry=true}else{decrease()}" style="width:' + _w + '; height:' + _h + '; position: absolute; max-width: 100% ;max-height: 100%; top: 0; right: 0; bottom: 0;  left: 0; margin:auto;"/>');
                } else {
                    mother.html('<img src="' + url + '" class="offer-img" onload="decrease()" onerror="if(this.secondTry!=true){this.src = noimg;this.secondTry=true}else{decrease()}" />');
                }
            } else {
                mother.html('<img src="' + url + '" style="width:100%; height:100%" onload="decrease()" onerror="if(this.secondTry!=true){this.src = noimg;this.secondTry=true}else{decrease()}"/>');
                if (logoContainer) mother.find('img').css('position', 'absolute').css('left', '0').css('right', '0').css('top', '0').css('bottom', '0').css('margin', 'auto');
            }
        } else {
            mother.html('<div class="div-image" id="div-image-' + id + '" ></div>');
            var divImg = $('#div-image-' + id);
            divImg.css("background-image", "url(\"" + url + "\")").css("background-position", "center").css("background-size", cover ? "cover" : "contain").css("background-repeat", "no-repeat").css("height", _h).css("width", _w);
            if (logoContainer) divImg.css('position', 'absolute').css('left', '0').css('right', '0').css('top', '0').css('bottom', '0').css('margin', 'auto');
            decrease();
        }
    }

    if (isIE && !forceDiv) {
        var xhr = new XMLHttpRequest();
        xhr.onload = function() {
            var url = URL.createObjectURL(this.response);
            img.onload = function() {
                makeImage(img);
                URL.revokeObjectURL(url);
            };
            img.src = url;
        };
        xhr.onerror = function() {
            if (!firstTry) {
                return;
            }
            firstTry = false;
            var url = noimg;
            img.onload = function() {
                makeImage(img);
                URL.revokeObjectURL(url);
            };
            cover = false;
            img.src = url;
        };
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.send();
        return;
    }
    if (!forceDiv) img.setAttribute('crossOrigin', 'anonymous');
    img.src = url;
    img.onload = function() {
        makeImage(img)
    };
    img.onerror = function() {
        if (!firstTry) {
            decrease();
            return;
        }
        firstTry = false;
        url = noimg;
        cover = false;
        img.src = url;
    };

    function makeImage(img) {
        if (!dontHide) fadeInElement(mother, 400, dontFade);

        var w1 = img.width ? img.width : w;
        var h1 = img.height ? img.height : h;
        if (isLogo) {
            mn = getLogoMarg(w, h, [w1, h1], img.width == 0 || img.height == 0);
            m = 1;
            w = mn.w;
            h = mn.h;
        }
        if ((!c || isMobile || forceDiv) && cover) {
            makeDiv(w, h);
            return;
        }

        var p = (w1 / h1) / (w / h);
        var w2, h2;
        if (cover) {
            if (p < 1) {
                w2 = w1;
                h2 = h1 * p;

            } else {
                w2 = w1 / p;
                h2 = h1;
            }
            canvas.width = w2;
            canvas.height = h2;
            c.drawImage(img, Math.round((w2 - w1) / 2), Math.round((h2 - h1) / 2));
            resample_hermite(canvas, canvas.width, canvas.height, w, h);
        } else {
            if (p < 1) {
                w2 = w * p;
                h2 = h;
            } else {
                w2 = w;
                h2 = h / p;
            }
            if (!logoContainer) {
                mother.css("margin-left", Math.round((w - w2) / 2 + mn.w) + "px").css("margin-top", Math.round((h - h2) / 2 + mn.h) + "px");
            } else {
                $(canvas).css('position', 'absolute').css('left', '0').css('right', '0').css('top', '0').css('bottom', '0').css('margin', 'auto');
            }
            if (!c || isMobile || forceDiv) {
                makeDiv(w2, h2);
                return;
            }
            canvas.width = w1;
            canvas.height = h1;
            c.drawImage(img, 0, 0);
            resample_hermite(canvas, w1 + m, h1 + m, w2, h2);
        }
        decrease();
    }
}

function resample_hermite(canvas, W, H, W2, H2) {
    var time1 = Date.now();
    W2 = Math.round(W2);
    H2 = Math.round(H2);
    var img = canvas.getContext("2d").getImageData(0, 0, W, H);
    var img2 = canvas.getContext("2d").getImageData(0, 0, W2, H2);
    var data = img.data;
    var data2 = img2.data;
    var ratio_w = W / W2;
    var ratio_h = H / H2;
    var ratio_w_half = Math.ceil(ratio_w / 2);
    var ratio_h_half = Math.ceil(ratio_h / 2);

    for (var j = 0; j < H2; j++) {
        for (var i = 0; i < W2; i++) {
            var x2 = (i + j * W2) * 4;
            var weight = 0;
            var weights = 0;
            var weights_alpha = 0;
            var gx_r = gx_g = gx_b = gx_a = 0;
            var center_y = (j + 0.5) * ratio_h;
            for (var yy = Math.floor(j * ratio_h); yy < (j + 1) * ratio_h; yy++) {
                var dy = Math.abs(center_y - (yy + 0.5)) / ratio_h_half;
                var center_x = (i + 0.5) * ratio_w;
                var w0 = dy * dy * dy;
                for (var xx = Math.floor(i * ratio_w); xx < (i + 1) * ratio_w; xx++) {
                    var dx = Math.abs(center_x - (xx + 0.5)) / ratio_w_half;
                    var w = Math.sqrt(w0 + dx * dx * dx);
                    if (w >= -1 && w <= 1) {;
                        weight = 2 * w * w * w - 3 * w * w + 1;
                        if (weight > 0) {
                            dx = 4 * (xx + yy * W);;
                            gx_a += weight * data[dx + 3];
                            weights_alpha += weight;
                            if (data[dx + 3] < 255)
                                weight = weight * data[dx + 3] / 250;
                            gx_r += weight * data[dx];
                            gx_g += weight * data[dx + 1];
                            gx_b += weight * data[dx + 2];
                            weights += weight;
                        }
                    }
                }
            }
            data2[x2] = gx_r / weights;
            data2[x2 + 1] = gx_g / weights;
            data2[x2 + 2] = gx_b / weights;
            data2[x2 + 3] = gx_a / weights_alpha;
        }
    }
    canvas.getContext("2d").clearRect(0, 0, Math.max(W, W2), Math.max(H, H2));
    canvas.width = W2;
    canvas.height = H2;
    canvas.getContext("2d").putImageData(img2, 0, 0);
}


function getLogoMarg(lw, lh, ls, dontCalc) {

    var mul = (forceLogoMargin || 0.11);

    var m = Math.min(lw, lh) * mul;


    if (!dontCalc) {
        if (ls[0] > 5 * ls[1] && lw > 5 * lh) {
            m *= 2.3;
        } else if (ls[0] > 4 * ls[1] && lw > 4 * lh) {
            m *= 2;
        } else if (ls[0] > 4 * ls[1] && lw > 3 * lh) {
            m *= 2.4;
        } else if (ls[0] > 3 * ls[1] && lw > 3 * lh) {
            m *= 1.5;
        } else if (ls[0] > 2 * ls[1] && lw > 2 * lh) {
            m *= 1.3;
        }
        if (ls[0] < 2 * ls[1] && lw > 2 * lh) {
            m *= 0.9;
        }
    }

    maxWidth = Math.floor(lw - Math.round(2 * Math.max(m, lw * mul)));
    maxHeight = Math.floor(lh - Math.round(2 * m));

    imgWidth = ls[0];
    imgHeight = ls[1];
    ratioHeight = maxHeight / imgHeight;
    imgHeight = maxHeight;
    imgWidth = Math.floor(imgWidth * ratioHeight);

    if (imgWidth > maxWidth) {
        ratioWidth = maxWidth / imgWidth;
        imgWidth = maxWidth;
        imgHeight = Math.floor(imgHeight * ratioWidth);
    }

    return {
        w: imgWidth,
        h: imgHeight
    };
}

function makeFormats(arr) {
    var formats = '[';
    for (var i = 0; i < arr.length; i++) {
        formats += arr[i].width + 'x' + arr[i].height + ((i < arr.length - 1) ? ', ' : ']')
    }
    return formats;
}
