

var windowWidth;
var windowHeight;
var bDisableScrollCall = false;
var header;

$(function () {

    //get the current window width:
    windowWidth = $(window).width();
    windowHeight = $(window).height();

    //set the header object:
    header = $(".topHeader");

    /*smooth scrolling */
    $('.leftnav a[href*=#]:not([href=#]):not([href=#drugalpha]):not([href=#conditionalpha]), .view-larger-image').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {

                var scrolltopval = (target.offset().top - $('.navbar').height()) - 10;

                bDisableScrollCall = true;

                HideTopHeaderDeferred().done(function () {
                    $('html,body').animate({
                        scrollTop: scrolltopval
                    }, 500, function () { bDisableScrollCall = false; });
                });
            }
        }
        return false;
    });

    $('.back-to-top').click(function () {
        $('html,body').animate({
            scrollTop: 0
        }, 500, function () {
            $('.back-to-top').fadeOut();
        }
        );

        return false;
    });


    //scroll to target from querystring
    var scrollto = strScrollTo;
    if (scrollto != '') {
        scrollto = '#' + scrollto;
        var target = $(scrollto);
        var scrolltopval = target.offset().top - 50;

        if (windowWidth >= 768)
            scrolltopval = scrolltopval - 103;

        bDisableScrollCall = true;

        HideTopHeaderDeferred().done(function () {
            $('html,body').animate({
                scrollTop: scrolltopval
            }, 500, function () { bDisableScrollCall = false; });
        });

    }




    //all scrolled events must execute in this function
    $(window).scroll(function () {
        WindowScrolled();
    });
});



$(function () {

    var domain = strDomain;

    //fix relative .asp links by adding correct domain
    $(".content-body a[href*='.asp']").not(".content-body a[href^='http']").each(function () {
        var url = $(this).attr('href');

        $(this).prop("href", domain + url);
    });

    //fix relative pdf links by adding correct domain
    $(".content-body a[href*='.pdf']").not(".content-body a[href^='http']").each(function () {
        var url = $(this).attr('href');

        $(this).prop("href", domain + url);
    });


    //fix relative img paths by adding correct domain
    $(".content-body img").not(".content-body img[src^='http'], .content-body img[src^='" + domain + "']").each(function () {
        var url = $(this).attr('src');

        $(this).prop("src", domain + url);
    });

    //fix path for flash objects
    $(".content-body param").each(function () {
        var url = $(this).attr('value');

        $(this).prop("value", domain + url);
    });
    $(".content-body embed").each(function () {
        var url = $(this).attr('src');

        $(this).prop("src", domain + url);
    });

    //fix old sup css:
    $(".content-body sup").css('vertical-align', 'middle');

    //fix figures
    $('.content-body .figure').css('width', '100%');

    //fix tables
    $('.content-body table').addClass('table');


    //fix header tags in content with higher tag if a higher tag doesn't exist
    if (!$('.article-body #accordion')) {
        if (!$(".article-body h2").length) {
            if (!$(".article-body h3").length) {
                if (!$(".article-body h4").length) {
                    $('.article-body h5').replaceWith(function () {
                        return "<h4>" + $(this).html() + "</h4>";
                    });
                }

                $('.article-body h4').replaceWith(function () {
                    return "<h3>" + $(this).html() + "</h3>";
                });
            }

            $('.article-body h3').replaceWith(function () {
                return "<h2>" + $(this).html() + "</h2>";
            });
        }
    }

    //adjust alpha search inputs for mobile:
    if (windowWidth < 768) {
        $('.search-content-keyword .input-group').removeClass('input-group-lg');
        $('.search-content-keyword .input-group i.fa-2x').removeClass('fa-2x');
    }

});


//sticky ads
var stickyAdNav = function () { };
function initStickyAdNav() {
    var stickyNavTop = $('.bglight').offset().top;

    var leftNavHeight = $('.bglight').height();
    var leftNavWidth = $('.bglight').width();

    stickyAdNav = function () {
        var scrollTop = $(window).scrollTop();
        var navbarHeight = $('#navbar').height() - 156;

        if (scrollTop > stickyNavTop) {
            if (scrollTop + $(window).height() >= $(document).height() - $('#cXense').height() - $('#footer').height())
                $('.bglight').removeClass('sticky-ad');
            else {
                $('.bglight').addClass('sticky-ad');
                $('.sticky-ad').css('width', leftNavWidth + 'px');
                $('.sticky-ad').css('top', navbarHeight + 'px');
            }
        } else {
            $('.bglight').removeClass('sticky-ad');
        }
    };

    stickyAdNav();
}

//sticky nav    
var stickyNav = function () { };
function initStickyNav() {
    var stickyNavTop = $('.leftnav').offset().top - 50;

    var leftNavHeight = $('.leftnav').height();
    var leftNavWidth = $('.leftnav').width();

    stickyNav = function () {
        if (windowWidth >= 991 && leftNavHeight < 787) {
            var scrollTop = $(window).scrollTop();
            var navbarHeight = $('#navbar').height() - 156;

            if (scrollTop > stickyNavTop) {
                if (scrollTop + $(window).height() >= $(document).height() - $('#cXense').height() - $('#footer').height())
                    $('.leftnav').removeClass('sticky');
                else {
                    $('.leftnav').addClass('sticky');
                    $('.sticky').css('width', leftNavWidth + 'px');
                    $('.sticky').css('top', navbarHeight + 'px');
                }
            } else {
                $('.leftnav').removeClass('sticky');
            }
        } else {
            $('.leftnav').removeClass('sticky');
        }
    };

    stickyNav();
}

//hide ads function
function HideAds() {
    $('#leaderboard-ad').hide();
    $('#ad-boxes-right').hide();
}

//load navigation
$.ajax({
    cache: false,
    type: "GET",
    url: strNavigation,
    data: {},
    success: function (data) {
        $('#navbar').html(data);

        var leaderboardheight = $('#leaderboard-ad').height();

        var desktopNavbarHeight = 123;
        var leaderboardBaseHeight = 100;

        if (windowWidth >= 768) {

            //desktop nav:
            if (leaderboardheight < leaderboardBaseHeight)
                leaderboardheight = leaderboardBaseHeight;
            //set the height of the header
            $(header).css('height', (leaderboardheight + desktopNavbarHeight) + 'px');

            //sometimes the leaderboard takes a while to load
            setTimeout(
                function () {
                    if ($('#leaderboard-ad').height() > leaderboardBaseHeight) {
                        $(header).css('height', ($('#leaderboard-ad').height() + desktopNavbarHeight) + 'px');
                    }

                    if ($('#leaderboard-ad').height() == 10) {
                        $(header).css('height', desktopNavbarHeight + 'px');
                        $('#leaderboard-ad').hide();
                    }


                    if (windowWidth < 970) {
                        //if (windowHeight - leaderboardheight < 720) {                            
                        $('.mega-menu .dropdown-menu').css('height', (windowHeight - leaderboardheight) + 'px').css('overflow-y', 'scroll');
                        //}
                    }
                }
                , 1000);
        }
        else {

            //mobile nav:

            var navheight = (windowHeight - 95);
            if (navheight > 275) navheight = 275;

            $(header).css('height', ($('#navbar').height()) + 'px');
            $('.navbar .nav').css('height', navheight + 'px');
        }

        if ($('.leftnav').length && !($('.top-search').length)) {
            initStickyNav();
        }

        initStickyAdNav();

        GetFooter();
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert('Failed to retrieve navigation');
    }
});

//load Survey
function GetSurveyScript(i, t, p) {
    //$.ajax({
    //    cache: false,
    //    type: "GET",
    //    url: strSurvey,
    //    data: {itemID: i, tableID: t, portalID: p},
    //    success: function (data) {
    //        //alert(data);
    //        $('#survey').html(data);
    //    },
    //    error: function (xhr, ajaxOptions, thrownError) {
    //        alert('Failed to retrieve Survey');
    //    }
    //});
}

//load footer
function GetFooter() {
    $.ajax({
        cache: false,
        type: "GET",
        url: strFooterNavigation,
        data: {},
        success: function (data) {
            $('#footer').html(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Failed to retrieve footer');
        }
    });
}

function HideTopHeaderDeferred() {
    var dfrd1 = $.Deferred();
    if (header.hasClass('topHeader')) {
        header.removeClass('topHeader').addClass("scrolledHeader");
        $('#leaderboard-ad').animate({ height: '0px' }, 300, function () { dfrd1.resolve(); }).css('visibility', 'hidden');
    } else {
        dfrd1.resolve();
    }


    return dfrd1.promise();
}

function HideTopHeader() {

    // if (header.hasClass('topHeader')) {
    //    header.removeClass('topHeader').addClass("scrolledHeader");
    //   $('#leaderboard-ad').animate({ height: '0px' }, 300).css('visibility', 'hidden');
    //}

}

function ShowTopHeader() {
    // header.removeClass('scrolledHeader').addClass('topHeader');
    // $('#leaderboard-ad').animate({ height: '100%' }).css('visibility', 'visible');
}

function WindowScrolled() {
    //showing the back to top button
    var scroll = $(window).scrollTop();

    if (scroll >= windowHeight)
        $('.back-to-top').fadeIn();
    else
        $('.back-to-top').fadeOut();


    //hide-show parts of header based on scroll
    if (windowWidth >= 768) {
        var scroll = $(window).scrollTop();

        if (!bDisableScrollCall) {
            if (scroll >= 100) {
                HideTopHeader();
            } else if (scroll < 100) {
                ShowTopHeader();
            }
        }
    }

    stickyNav();
    stickyAdNav();
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}


function completeRequest(data) {
    var result = $.parseJSON(data.responseText);

    if (result != 'undefined' && result != null && result.error) {
        // just display error and not replace  all content
        // attachModelError is my custom method, it just adds vlaidation-error class to inputs, etc.
        attachModelError("my-input", result.error);
        return;
    }

    // or show returned html (depending on returned model form inputs will be modified:
    // select box with different items in my case
    $('#PartialDiv').html(data.responseText);
}

// START : Newsletter

$('#emailsignup').on('input', function () {
    var input = $(this);
    var is_name = input.val();
    if (is_name) { input.removeClass("invalid").addClass("valid"); }
    else { input.removeClass("valid").addClass("invalid"); }
});

var recaptchaContact;
var recaptchaNews;

var CaptchaCallback = function () {

    if ($('#rcaptchaContact').length) {
        recaptchaContact = grecaptcha.render('rcaptchaContact', { 'sitekey': '6LcV6goTAAAAAHTE4hK-KKtTGy6pBAbphDGmr8Zx' });
    }
    if ($('#rcaptchaNews').length) {
        recaptchaNews = grecaptcha.render('rcaptchaNews', { 'sitekey': '6LcV6goTAAAAAHTE4hK-KKtTGy6pBAbphDGmr8Zx' });
    }
};


$('#btnSignup').click(function () {

    //var patt = /^[a-zA-Z0-9+&*-]+(?:\.[a-zA-Z0-9_+&*-]+)*@@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,7}$/;
    var patt = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var email = $('#emailsignup').val();

    //var grecaptcha = $('#g-recaptcha-response').val();

    //alert("newletter : " + grecaptcha.getResponse(recaptchaNews).length);

    var msg = "";
    if (email.length <= 0 || !patt.test(email)) {
        $("#errorEmail").css("display", "block");
        msg += "You have entered an invalid email address. \n\n";
    } else {
        $("#errorEmail").css("display", "none");
    }
    if ($("#checkPrivacy").prop('checked') == false) {
        $("#errorPrivacy").css("display", "block");
        msg += "In order to receive our newsletter, please indicate that you accept the terms of our Privacy Policy. \n\n";
    } else {
        $("#errorPrivacy").css("display", "none");
    }
    if (grecaptcha.getResponse(recaptchaNews).length <= 0) {
        $("#errorCaptcha").css("display", "block");
        msg += "In order to receive our newsletter, please check the box marked \" I'm not a robot \". \n";
    } else {
        $("#errorCaptcha").css("display", "none");
    }
    if (msg != "") {
        //alert(msg);
        return false;
    }


    return true;
});

// END : Newsletter

function paging(sp) {
    var pass;
    var tracker = localStorage.getItem("tracker");
    if (tracker != null) {
        sp = parseInt(tracker);
        pass = true;
    }
    else if (sp != 1) {
        localStorage.setItem("tracker", sp);
        var location = window.location.href;
        window.location.assign(location);
        pass = false;
    }
    else if (sp === 1) {
        pass = true;
    }

    if (pass) {
        var initialVal = 0 + (sp - 1) * 20;
        var finalVal = initialVal + 20;
        var list = "";
        var j
        if (finalVal > k.length) {
            j = k.length;
        } else {
            j = finalVal;
        }
        for (var i = initialVal; i < j; i++) {
            list = list + k[i].outerHTML;
        }
        elems[0].innerHTML = "";
        elems[0].innerHTML = list;
    }
}

function applyPaging(totals) {
    var tracker = localStorage.getItem("tracker");
    var pageNo = 1;
    if (tracker != null) {
        pageNo = parseInt(tracker);
        localStorage.removeItem("tracker");
    }
    $('#paging-selection').bootpag({
        total: totals,
        page: pageNo,
        maxVisible: 5,
        activeClass: 'active',
        disabledClass: 'disabled',
        nextClass: 'next',
        prevClass: 'prev',

    }).on("page", function (event, /* page number here */ num) {

        paging(num);
    });

}


/* START: StickyFooter */

var scrolling = false;
var previousTop = 0;
var currentTop = 0;
var scrollDelta = 10;
var scrollOffset = 150;

$(window).on('scroll', function () {
    if (!scrolling) {
        scrolling = true;
        (!window.requestAnimationFrame) ?
            setTimeout(autoHideHeader, 250) : requestAnimationFrame(autoHideHeader);
    }
});
//scroll check
function scrollCheck(currentTop) {

    if (previousTop - currentTop > scrollDelta) {

        // Scroll up
        $('#stickyFooter').removeClass('hiddenStickyFooter');

    } else if (currentTop - previousTop > scrollDelta && currentTop > scrollOffset) {

        // Scroll down...
        $('#stickyFooter').addClass('hiddenStickyFooter');
        $('body').attr("style", "padding-bottom:0px");

    }
}

//auto hiding function
function autoHideHeader() {
    var currentTop = $(window).scrollTop();

    scrollCheck(currentTop);

    previousTop = currentTop;
    scrolling = false;
}

/* END: StickyFooter */


/* START : CXense script */



function add3Dots(string, limit) {
    var dots = "...";
    var words = string.split(' ');
    var substring = "";

    for (var n = 0; n < 15; n++) {
        substring += words[n] + " ";
    }
    //if (string.length > limit) {
    //    string = string.substring(0, limit) + dots;
    //}

    return substring.trim() + dots;
}

var WIDGET_ID_internalClinical = 'ad03968d8b806557dcc4049c90b90113520f5afa';      //widget Id
var WIDGET_ID_internalNews = '4adcd1c5655ecfaadc74b72c4ab1d4d826116383';      //widget Id
var WIDGET_ID_external = '8d5775858bd9ba9b17ef8b584b2be3a71f8c07c9';      //widget Id

function myRenderFunctionInternal1(data, context) {
    var targetId = context.targetElementId;

    for (i = 0; i < data.response.items.length; i++) {
        //For each recommendation, obtain the title, the url, the image
        var recPageTitle = data.response.items[i]["recs-que-title"];
        var recPageUrl = data.response.items[i]["url"];
        var recClickUrl = data.response.items[i]["click_url"];
        var recPageImageUrl = data.response.items[i]["recs-image"];
        var recPageDescription = data.response.items[i]["description"];
        var recSource = "";

        // If external we add UTM parameters and the source (host) of the recommendation
        var rec_url = document.createElement('a');
        rec_url.href = recPageUrl;



        //  Compose the html of each individual content recommendation
        var recContent = "";

        recContent += "<div class='recSubDiv'>";
        recContent += "<a href='" + recClickUrl + "'> ";
        if (recPageUrl.indexOf("/procedure/") > 0) {
            recContent += "<img src='http://ressourcessante.salutbonjour.ca/images/icon_tests_grey.svg' />  EXAMENS ET PROCÉDURES";
        }
        if (recPageUrl.indexOf("/drug/") > 0) {
            recContent += "<img src='http://ressourcessante.salutbonjour.ca/images/icon_drugs_grey.svg' />  MÉDICAMENTS";
        }
        if (recPageUrl.indexOf("/condition/") > 0) {
            recContent += "<img src='http://ressourcessante.salutbonjour.ca/images/icon_condition_grey.svg' />  AFFECTIONS";
        }
        recContent += " <figure class='reco-img'>";
        //recContent += " <img src='" + recPageImageUrl + "' alt='" + recPageTitle + "' border='0' width='255' height='101'>";
        recContent += " </figure>";
        recContent += " <div class='text'>";
        recContent += " <h3 class='reco-title'>" + recPageTitle + "</h3>";
        recContent += "<p style='color:#000;'>" + add3Dots(recPageDescription, 100) + "</p>";
        recContent += recSource;
        recContent += " </div>";
        recContent += "</a>";
        recContent += "</div>";

        //  Add the individual content recommendation created above to the set of recommendations
        var div = document.createElement('div');
        div.id = "recDiv" + i;
        div.className = "col-md-3 col-sm-6 col-xs-6";      //  This line configure the bpptstrap framework's behavior

        if (windowWidth <= 768) {
            if (i == 0 || i == 1) {
                div.className = "col-md-3 col-sm-6 col-xs-6 recDiv1";
            }
            else {
                div.className = "col-md-3 col-sm-6 col-xs-6 recDiv2";
            }
        }

        div.innerHTML = recContent;
        document.getElementById(targetId).appendChild(div);

    }

    if (windowWidth <= 768) {
        $("#internalClinical .recDiv1").wrapAll("<div class='row outerdiv' />");
        $("#internalClinical .recDiv2").wrapAll("<div class='row outerdiv' />");
    }
}

function myRenderFunctionInternal2(data, context) {
    var targetId = context.targetElementId;

    for (i = 0; i < data.response.items.length; i++) {
        //For each recommendation, obtain the title, the url, the image
        var recPageTitle = data.response.items[i]["recs-que-title"];
        var recPageUrl = data.response.items[i]["url"];
        var recClickUrl = data.response.items[i]["click_url"];
        var recPageImageUrl = data.response.items[i]["recs-image"];
        var recSource = "";

        // If external we add UTM parameters and the source (host) of the recommendation
        var rec_url = document.createElement('a');
        rec_url.href = recPageUrl;


        //  Compose the html of each individual content recommendation
        var recContent = "";

        recContent += "<a href='" + recClickUrl + "'> ";
        recContent += " <figure class='reco-img'>";
        recContent += " <img src='" + recPageImageUrl + "' alt='" + recPageTitle + "' border='0'>";
        recContent += " </figure>";
        recContent += " <div class='text'>";
        if (recPageUrl.indexOf("/healthfeature/") > 0) {
            recContent += "<p class='title'>CAPSULES SANTÉ</p>";
        }
        if (recPageUrl.indexOf("/news/") > 0) {
            recContent += "<p class='title'>ACTUALITÉS</p>";
        }
        recContent += " <p class='reco-title'>" + recPageTitle + "</h3>";
        recContent += recSource;
        recContent += " </div>";
        recContent += "</a>";




        //  Add the individual content recommendation created above to the set of recommendations
        var div = document.createElement('div');

        div.id = "recDiv" + i;
        div.className = "col-md-3 col-sm-6 col-xs-6";      //  This line configure the bpptstrap framework's behavior

        if (windowWidth <= 768) {
            if (i == 0 || i == 1) {
                div.className = "col-md-3 col-sm-6 col-xs-6 recDiv1";
            }
            else {
                div.className = "col-md-3 col-sm-6 col-xs-6 recDiv2";
            }
        }

        div.innerHTML = recContent;
        document.getElementById(targetId).appendChild(div);

    }

    if (windowWidth <= 768) {
        $("#internalNews .recDiv1").wrapAll("<div class='row outerdiv' />");
        $("#internalNews .recDiv2").wrapAll("<div class='row outerdiv' />");
    }
}

function myRenderFunctionExternal(data, context) {
    var targetId = context.targetElementId;

    for (i = 0; i < data.response.items.length; i++) {
        //For each recommendation, obtain the title, the url, the image
        var recPageTitle = data.response.items[i]["title"];
        var recPageUrl = data.response.items[i]["url"];
        var recClickUrl = data.response.items[i]["click_url"];
        var recPageImageUrl = data.response.items[i]["recs-image"];
        var recSource = "";

        // If external we add UTM parameters and the source (host) of the recommendation
        var rec_url = document.createElement('a');
        rec_url.href = recPageUrl;

        external_site_param = '?utm_source=sante.canoe.ca&utm_medium=cxense&utm_campaign=reco';
        recClickUrl = recClickUrl + external_site_param;
        recSource = "<p class='reco-src'>" + rec_url.hostname + "</p>";


        //  Compose the html of each individual content recommendation
        var recContent = "";
        recContent += "<a href='" + recClickUrl + "' target='_blank'> ";
        recContent += " <figure class='reco-img'>";
        recContent += " <img src='" + recPageImageUrl + "' alt='" + recPageTitle + "' border='0' width='255' height='101'>";
        recContent += " </figure>";
        recContent += " <div class='text'>";
        recContent += recSource;
        recContent += " <p class='reco-title'>" + recPageTitle + "</p>";

        recContent += " </div>";
        recContent += "</a>";


        //  Add the individual content recommendation created above to the set of recommendations
        var div = document.createElement('div');
        div.id = "recDiv" + i;
        div.className = "col-md-3 col-sm-6 col-xs-6";      //  This line configure the bpptstrap framework's behavior

        if (windowWidth <= 768) {
            if (i == 0 || i == 1) {
                div.className = "col-md-3 col-sm-6 col-xs-6 recDiv1";
            }
            else {
                div.className = "col-md-3 col-sm-6 col-xs-6 recDiv2";
            }
        }

        div.innerHTML = recContent;
        document.getElementById(targetId).appendChild(div);

    }
    if (windowWidth <= 768) {
        $("#externalArticle .recDiv1").wrapAll("<div class='row outerdiv' />");
        $("#externalArticle .recDiv2").wrapAll("<div class='row outerdiv' />");
    }
}

var cX = cX || {};
cX.callQueue = cX.callQueue || [];
//cX.callQueue.push(['insertWidget', { widgetId: WIDGET_ID_internalClinical, renderFunction: myRenderFunctionInternal1, targetElementId: 'internalClinical' }]);
cX.callQueue.push(['insertWidget', { widgetId: WIDGET_ID_internalNews, renderFunction: myRenderFunctionInternal2, targetElementId: 'internalNews' }]);
cX.callQueue.push(['insertWidget', { widgetId: WIDGET_ID_external, renderFunction: myRenderFunctionExternal, targetElementId: 'externalArticle' }]);


(function (d, s, e, t) {
    e = d.createElement(s);
    e.type = "text/Java" + s;
    e.async = "async";
    e.src = 'http' + ('https:' === location.protocol ? 's://s' : '://') + 'cdn.cxense.com/cx.js';
    t = d.getElementsByTagName(s)[0];
    t.parentNode.insertBefore(e, t);
});

/* ENDS : CXense script*/
