/* Minification failed. Returning unminified contents.
(333,89-90): run-time error JS1195: Expected expression: *
 */
+function(i,t,e){"use strict";var s={size:{min:.1,max:10,default:1},shrink:{min:.2,max:1,default:.8},regrow:{min:.2,max:1,default:.8},minRows:{min:1,max:99,default:1},maxRows:{min:1,max:99,default:2},prefixReserve:{min:0,max:.8,default:.3},prefixHide:{min:.1,max:10,default:2},alignRight:{type:"boolean",default:!1}},n=function(){var i=t.fn.jquery.split(".");return 1==i[0]&&i[1]<8}();i.rrssbConfigAll=function(i){t(".rrssb").each(function(){t(this).rrssbConfig(i)})},t.fn.rrssbConfig=function(i){if(!t(this).data("settings")||i){var e={};for(var n in s)e[n]=s[n].default,i&&("boolean"==s[n].type?e[n]=Boolean(i[n]):isNaN(parseFloat(i[n]))||(e[n]=Math.min(s[n].max,Math.max(s[n].min,i[n]))));t(this).data("settings",e),h.call(this)}};var r,a=function(){t(".rrssb").each(h)},h=function(){var i=t(this).data("orig");i||(i=function(){var i=t(".rrssb-prefix",this),e=i.length?i.clone().css({visibility:"hidden","white-space":"nowrap",display:"inline"}).appendTo(this):null;t("ul").contents().filter(function(){return this.nodeType===Node.TEXT_NODE}).remove();var s={width:0,buttons:0,height:t("li",this).innerHeight(),fontSize:parseFloat(t(this).css("font-size")),prefixWidth:e?e.innerWidth():0};return t("li",this).each(function(){s.width=Math.max(s.width,t(this).innerWidth()),s.buttons++}),t(this).data("orig",s),e&&e.remove(),s}.call(this));var e=t(this).data("settings"),s=i.width*e.size,r=i.buttons,a=t(this).innerWidth()-1,h=a<s*e.shrink?"":s;n?t("li",this).width(h):t("li",this).innerWidth(h);var o=a/e.shrink,l=i.prefixWidth*e.size;l>o*e.prefixHide?(l=0,t(".rrssb-prefix",this).css("display","none")):t(".rrssb-prefix",this).css("display","");var c=l<=a*e.prefixReserve?o-l:o,f=Math.floor(c/s);f*e.maxRows<r?(t(this).addClass("no-label"),s=i.height*e.size,f=Math.max(1,Math.floor(c/s))):t(this).removeClass("no-label");var d=e.minRows>1?Math.max(1,Math.ceil(r/(e.minRows-1))-1):r;f=Math.min(f,d),f=Math.ceil(r/Math.ceil(r/f)),d=Math.ceil(r/Math.ceil(r/d));var u=Math.floor(1e4/f)/100;t("li",this).css("max-width",u+"%");var m=s*f+l;m>o&&(m-=l,l=0);var p=f<d?e.regrow:1,g=Math.min(p,a/m),b=i.fontSize*e.size*g*.98;if(t(this).css("font-size",b+"px"),l){var x=Math.floor(1e4*l/m)/100;t(".rrssb-buttons",this).css("padding-left",x+"%"),t(".rrssb-prefix",this).css("position","absolute");var v=Math.ceil(r/f)*i.height/i.fontSize;t(".rrssb-prefix",this).css("line-height",v+"em")}else t(".rrssb-buttons",this).css("padding-left",""),t(".rrssb-prefix",this).css("position",""),t(".rrssb-prefix",this).css("line-height","");var w=e.alignRight?"padding-left":"padding-right";if(g>=.999*p){var M=Math.floor(1e4*(a-m*g*1.02)/a)/100;t(this).css(w,M+"%")}else t(this).css(w,"")},o=function(i){r&&clearTimeout(r),r=setTimeout(a,i||200)};t(document).ready(function(){t(".rrssb-buttons a.popup").click(function(e){!function(t,e,s,n){var r=void 0!==i.screenLeft?i.screenLeft:screen.left,a=void 0!==i.screenTop?i.screenTop:screen.top,h=(i.innerWidth?i.innerWidth:document.documentElement.clientWidth?document.documentElement.clientWidth:screen.width)/2-s/2+r,o=(i.innerHeight?i.innerHeight:document.documentElement.clientHeight?document.documentElement.clientHeight:screen.height)/3-n/3+a,l=i.open(t,e,"scrollbars=yes, width="+s+", height="+n+", top="+o+", left="+h);l&&l.focus&&l.focus()}(t(this).attr("href"),t(this).find(".rrssb-text").html(),580,470),e.preventDefault()}),t(i).resize(o),t(document).ready(function(){rrssbConfigAll()})})}(window,jQuery);;
$(document).ready(function () {
    //SocialShareKit.init();
    //share();
    loadReadon()

    responseveIframe();
    responseveShare();
});

function loadReadon() {
    var e = $('#readon');
    $.ajax({
        url: isHebrew() + "/home/PageReadon",
        traditional: true,//enable send of array
        data: { 'tagIdArr': e.data('chosentags'), 'type': e.data('type'), 'id': e.data('id') },
        dataType: "html",
        success: function (html) {
            $('#readon').append(html).fadeIn(500);
            checkLazyImgs();
        },
        error: function (xhr, status, error) {
            console.log("An AJAX error occured: " + status + "\nError: " + error + "\nError detail: " + xhr.responseText);
        }
    });
}

//---------------------------------------------------------- Resposive -------------------------------------------------------

$(window).resize(function () {
    responseveIframe();
    responseveShare();
});

//---------------------------------------------------- iframe (youtube/pdf) responsive ----------------------------------------------------------
function responseveIframe() {
    $("iframe,img").each(function () {
        //wantedHeight = (originalHeight / originalWidth) * currentWidth
        $(this).height(($(this).attr("height") / $(this).attr("width")) * $(this).width());
    })
}
//---------------------------------------------------- iframe pdf new window open ----------------------------------------------------------
$('<span class="pdfIframe">View pdf in full window</span>').insertBefore('iframe[src$=".pdf"]');
$('.pdfIframe').click(function () {
    var src = $(this).next().attr('src');
    window.open(src, "pdfIframe", "width=" + screen.availWidth + ",height=" + screen.availHeight);
})

//---------------------------------------------------- share page responsive ----------------------------------------------------------

//function responseveShare() {
//    if ($('#pageShare').length) {
//        if ($(window).width() < 520) {
//            if ($('#pageShare').hasClass('ssk-right')) {
//                $('#pageShare').removeClass('ssk-right').addClass('ssk-bottom ssk-sm pageShareSmall');
//            }
//        }
//        else if ($('#pageShare').hasClass('ssk-bottom')) {
//            $('#pageShare').removeClass('ssk-bottom ssk-sm pageShareSmall').addClass('ssk-right');
//        }
//    }
//}

function responseveShare() {
    if ($(window).width() < 520) {
        $('#share').removeClass("shareRight").addClass("shareBottom");
        $('.rrssb-print,.rrssb-reddit,.rrssb-pinterest').show();
        if ($(window).width() > 430) {
            $('.rrssb-print,.rrssb-reddit,.rrssb-pinterest').hide();
        }
    }
    else {
        $('#share').removeClass("shareBottom").addClass("shareRight");
        $('.rrssb-print,.rrssb-reddit,.rrssb-pinterest').show();
    }
    $('#share').show();
}

$('#share li').mouseenter(function () {
    var href = $(this).find('a').attr('href').toString();
    var isTweet = $(this).hasClass("rrssb-twitter");
    var desc = document.querySelector('meta[name="description"]').content;
    desc = isTweet && desc.length > 230 ? "" : desc;
    href = href
    .replace('{title}', document.title)
    .replace('{url}', window.location.href)
    .replace('{desc}', desc)
    .replace('{media}', document.querySelector('meta[name="image"]').content)
    .replace('{body}', desc + '%0ARead at: ' + window.location.href);
    $(this).find('a').attr('href', href);
})

//function share() {
//    $('.rrssb-buttons').rrssb({
//        // required:
//        title: document.title,
//        url: window.location.href,

//        // optional:
//        description: document.querySelector('meta[name="description"]').content,
//        emailBody: document.querySelector('meta[name="description"]').content + '<br>Read more: ' + window.location.href
//    });
//}

function printIt() {
    var pre = '<div style="display:flex;justify-content:space-between;"><img src="/content/images/logofull.png" width="161" height="55"><br><small>' + window.location.href + '</small></div><article class="pageBody">';
    var post = "</article>";
    var article = document.querySelector("article").innerHTML;
    var bodyHtml = document.body.innerHTML;
    var title = document.title;
    var bodyElement = document.querySelector('body');
    var bgColor = window.getComputedStyle(bodyElement).backgroundColor;
    var pageBodyBox = window.getComputedStyle(document.querySelector(".pageBody")).boxShadow;
    //set
    document.body.innerHTML = pre + article + post;
    bodyElement.style.backgroundColor = "white";
    document.title = "Palestinian Media Watch";
    document.querySelector(".pageBody").style.boxShadow = "0 0 0 white";
    setTimeout(function () {
        //restore
        window.onafterprint = function () {
            document.body.innerHTML = bodyHtml;
            document.title = title;
            bodyElement.style.backgroundColor = bgColor;
            document.querySelector(".pageBody").style.boxShadow = pageBodyBox;
        }
        window.print();
    }, 1000);
}
;
$(document).ready(() => {
    if (window.location.hash && document.querySelector(".yt-img-container")) {
        youtubeThumbnailClicked(window.location.hash);
    }
});

/*---------------------------------------------------- Thumbnail to video --------------------------------------------------------*/
var currntYTid;
document.querySelectorAll(".yt-img").forEach((el) => {
    el.parentNode.onclick = (e) => e.preventDefault();
    el.onclick = (e) => youtubeThumbnailClicked(e);
});

function youtubeThumbnailClicked(e) {
    let el;
    if (e.target)
        el = e.target;
    else if (document.querySelector(`[data-ytid="${e.substring(1)}"]`))
        el = document.querySelector(`[data-ytid="${e.substring(1)}"]`);
    else return;// some youtube ids dont work as selector id

    let t = document.createElement("iframe");
    currntYTid = el.id;
    t.id = "yt_" + currntYTid;
    t.setAttribute(
        "src",
        "https://www.youtube.com/embed/" +
        el.id +
        "?rel=0&modestbranding=1&enablejsapi=1"
    );//autoplay=1& only worked in ff
    t.setAttribute("frameborder", "0");
    t.style.cssText = el.style.cssText;//for aspectRatio 
    if (window.location.href.indexOf("page") == -1)
        t.style.width = "100%";
    else
        t.setAttribute("width", el.getAttribute("width"));
    //t.addEventListener("load", () => {
    //    let player = new YT.Player(currntYTid, {
    //        events: {
    //            onReady: () => player.playVideo()
    //        }
    //    });
    //});

    el.parentNode.parentNode.replaceChildren(t);
    if (window.location.hash.includes(currntYTid))//only when came from out of website, not click
        t.scrollIntoView();
    YTapiStuff();
    //loadYtapi();
};

function onYouTubeIframeAPIReady() {//this is called from iframe_api
    let player = new YT.Player("yt_" + currntYTid, {
        events: {
            onReady: () => {
                player.mute(); // wont start if not mute
                player.playVideo();
            }
        }
    });
}

function YTapiStuff() {
    if (window.YT && window.YT.Player) {
        onYouTubeIframeAPIReady();
    } else {
        // Load the YouTube Iframe API if not already loaded
        let tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        let firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
    }
}

//function loadAndPlayVideo() {
//    window.YT.ready(() => {
//        var player = new YT.Player("yt_" + currntYTid, {
//            events: {
//                onReady: () => {
//                    player.mute(); // wont start if not mute
//                    player.playVideo();
//                }
//            }
//        });
//    });
//}

//function loadYtapi() {
//    var tag = document.createElement("script");
//    tag.src = "https://www.youtube.com/iframe_api";
//    tag.id = "yt_iframe_api";
//    var firstScriptTag = document.getElementsByTagName("script")[0];
//    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//    whenAvailable("YT", loadAndPlayVideo)
//}

//function whenAvailable(name, callback) {
//    console.log('checking ' + name);
//    var interval = 100; // ms
//    window.setTimeout(function () {
//        if (window[name]) {
//            callback(window[name]);
//        } else {
//            whenAvailable(name, callback);
//        }
//    }, interval);
//}


/*---------------------------------------------------- Slider --------------------------------------------------------*/
let imgCount = document.querySelectorAll("#slider img").length;
if (imgCount > 0) {
    let perCent = 0;
    let mouseOnSlide = false;
    let pauseSlider = false;
    let slideRun;
    //set space based on number of images
    document.querySelector("#slider figure").style.width = `${(imgCount + 1) * 100}%`;
    document.querySelector("#slider figure").style.gridTemplateColumns = `repeat(${imgCount + 1}, 1fr)`;

    //add first image to the end for smooth transition to back to first slide
    let firstImgClone = document
        .querySelector("#slider figure").firstElementChild
        .cloneNode(true);
    document.querySelector("#slider figure").append(firstImgClone);
    //display first image description
    document.querySelector(
        "figureDescription"
    ).innerText = document
        .querySelector(`#slider a:nth-of-type(1) img`)
        .getAttribute("alt");

    //add img buttons on bottom and play/pause
    let imgJumper = document.createElement("div");
    imgJumper.id = "imgJumper";
    //play/pause
    let pauseBtn = document.createElement("button");
    pauseBtn.innerText = "Pause";
    pauseBtn.id = "pauseBtn";
    pauseBtn.onclick = pauseIt;
    imgJumper.append(pauseBtn);
    //imgs
    for (i = 1; i < imgCount + 1; i++) {
        let span = document.createElement("span");
        span.dataset.count = i;
        imgJumper.append(span);
    }
    document.querySelector("#sliderCon").append(imgJumper);

    startSliderIn(4000);
    //mouse on slide
    document
        .querySelector("#slider")
        .addEventListener("mouseover", () => (mouseOnSlide = true));
    // mouse leave slide
    document.querySelector("#slider").addEventListener("mouseleave", () => {
        if (pauseSlider) return;
        mouseOnSlide = false;
        clearTimeout(slideRun);
        startSliderIn(1500);
    });

    //jump to img
    document.querySelectorAll("#imgJumper span").forEach((el) => {
        el.addEventListener("click", (e) => {
            perCent = -100 * e.currentTarget.dataset.count + 102;
            clearTimeout(slideRun);
            startSliderIn(10);
        });
    });

    function moveit() {
        perCent -= 2;
        if (mouseOnSlide) perCent = Math.round((perCent + 30) / 100) * 100; //added 30 to tend to chatch the leaving img
        document.documentElement.style.setProperty("--slider-left", perCent + "%");
        if (perCent == imgCount * -100) {
            perCent = 0;
        }

        document
            .querySelector("figureDescription")
            .classList.toggle("fade", perCent % 100 != 0);
        document
            .querySelectorAll(`#imgJumper span`)
            .forEach((el) => (el.style.backgroundColor = "#9e9e9e"));

        if (perCent % 100 == 0) {
            document.querySelector(
                "figureDescription"
            ).innerText = document
                .querySelector(`#slider a:nth-of-type(${(perCent - 100) / -100}) img`)
                .getAttribute("alt");
            document.querySelector(
                `#imgJumper span:nth-of-type(${perCent == 0 ? 1 : perCent / -100 + 1})`
            ).style.backgroundColor = "#636363";

            if (mouseOnSlide || pauseSlider) return;
        }

        startSliderIn(perCent % 100 == 0 ? 4000 : 200 * (((perCent % 100) + 50) / 100) ** 2);
    }

    function startSliderIn(milis) {
        slideRun = setTimeout(moveit, milis);
    }

    function pauseIt() {
        mouseOnSlide = true; // so we dont stop in middel of image
        pauseSlider = !pauseSlider;
        document.querySelector("#pauseBtn").innerText = pauseSlider ? "Play" : "Pause";
        if (!pauseSlider) {
            mouseOnSlide = false;
            startSliderIn(500);
        }
    }
}

/*---------------------------------------------------- home impact --------------------------------------------------------*/

//    $.ajax({
//        url: "/home/HomeImpact",
//        dataType: "html",
//        success: function (html) {
//            $('#impact').append(html).fadeIn(500);
//            checkLazyImgs();
//        },
//        error: function (xhr, status, error) {
//            cLog(xhr, status, error);
//        }
//    });

//function cLog(xhr, status, error) {
//    console.log("AJAX error: " + status + "\nError: " + error + "\nDetail: " + xhr.responseText);
//};
