/*global net, SF, _, $, ga, immersion_adcode, console */

SF.Ads.isEnterpriseVisitor = function() {
    if (!immersion_adcode) {
        return false;
    }
    return (immersion_adcode.indexOf('accelacomm') >= 0 ||
            immersion_adcode.indexOf('/teras.') >=0 ||
            immersion_adcode.indexOf('madisonlogic') >=0 ||
            immersion_adcode.indexOf('library.slashdotmedia.com') >=0
            );
};

SF.Ads.isLeadgenImmersion = function() {
    // for now it is this simple, but may change.
    return SF.Ads.isEnterpriseVisitor();
};

SF.Ads.wireWrapperResize = function(wrapperSelector, containerSelector) {
    function wrapperResize($wrapper) {
        var width = $(window).width();
        $wrapper.css('width', width).css('margin-left', function() { return width / 2 * -1; });
    }

    var $wrapper = $(wrapperSelector);
    if ($wrapper.length) {
        $(containerSelector).addClass('with-wrapper');
        wrapperResize($wrapper);
        $(window).resize(function() {
            wrapperResize($wrapper);
        });
    }
};

SF.Ads.wireWindowOnError = function(){
    if (SF.Ads.isEnterpriseVisitor()) {
        SF.jsErrorLogged = false;
        window.onerror = function (msg, url, line) {
            if (!SF.adblock && !SF.jsErrorLogged) {
                SF.jsErrorLogged = true;
                SF.log.info('JS error: ' + msg + ' on line ' + line + ' of ' + url);
            }
        };
    }
};

SF.Ads.recordImmersionCall = function(selectorDFPNode, immersion_adcode, isGPT){
    if (SF.Ads.isEnterpriseVisitor()) {
        window.$dfpNode = $(selectorDFPNode);
        window.spacesRE = new RegExp('\\s+', 'g');
        window.quotesRE = new RegExp('"', 'g');
        if (isGPT || window.$dfpNode.length) {
            window.immersionSrc = window.$dfpNode.attr('src');
            window.sanitizedAdcode = immersion_adcode.replace(window.spacesRE, ' ').replace(window.quotesRE, '\'');
            var message = ['dfp_call="' + window.immersionSrc + '"',
                           'immersion_adcode="' + window.sanitizedAdcode + '"'].join(';');
            SF.log.info('Immersion call: ' + message);
            //console.log(message);
        }
    }
};


SF.Ads.postImmersionAd = function(immersion_adcode, selectorImmersion, selectorFallback){
    //show or hide immersion ad / fallback template
    var container,
        isSidebarPresent = function() {
            return container.children('.sidebar').length;
        },
        isSidebarPopulated = function() {
            return (container.find('.sidebar .accordion').length ||
                    container.find('.sidebar .sidebar-widget').css('display') === 'block');
        };

    if (immersion_adcode) {
        container = $(selectorImmersion);
        container.show();
        if (isSidebarPresent() && isSidebarPopulated()) {
            container.addClass('with-sidebar');

            if (SF.Ads.isLeadgenImmersion()) {
                if (SF.Ads.WideLeadgenLayout) {
                    // if wide leadgen layout feature enabled, hide the sidebar entirely.
                    container.find('.sidebar').hide();
                    container.find('.sterling').addClass('wide-leadgen');
                } else {
                    //for leadgen, we want the sidebar to appear, but only with the single medrec in it.
                    container.find('.sidebar > :not(.unit)').hide();
                    container.children('.sidebar').show();
                }
            }
            else {
                container.children('.sidebar').show();
            }
        }

        SF.Ads.pushTemplateImpressionBeacon('Template1');

    } else {
        SF.Ads.showFallbackTemplate();   //all this does is show the container.
    }

    SF.Ads.showContentForAdblock();

    //if this is a leadgen immersion, record details to server log.
    if (SF.Ads.isEnterpriseVisitor()){
        if (window.$dfpNode.length) {
            // Log details about how demandbase info was used
            var msg = '';
            if (!immersion_adcode && $('#p83_medrec').children().length > 1) {
                msg += 'Non-immersion ads served: ';
            }
            if (!immersion_adcode) {
                msg += 'Immersion adcode was empty: ';
            }
            if (immersion_adcode && (immersion_adcode.indexOf('accelacomm') < 0 && immersion_adcode.indexOf('/teras.') < 0 && immersion_adcode.indexOf('library.slashdotmedia.com') < 0)) {
                msg += 'Regular immersion ad requested: ';
            }
            if ($('img[src*="817-grey.gif"]').length) {
                msg += 'Default ad served: ';
            }
            if (msg) {
                var dfpResponse = $('<div></div>').html(window.$dfpNode.siblings().clone().slice(1,-1)).html();
                dfpResponse = dfpResponse.replace(window.spacesRE, ' ').replace(window.quotesRE, '\'');
                msg += ['dfp_request="' + window.immersionSrc + '"',
                        'dfp_response="' + dfpResponse + '"',
                        'immersion_adcode="' + window.sanitizedAdcode + '"'].join(';');
                SF.log.info(msg);
            }
        }
        // Log ad blocking
        if (SF.adblock) {
            SF.log.info('Ad blocker enabled: ');
        }
    }
};


SF.Ads.showContentForAdblock = function(){
    //the ads have already been written; just need to show it.
    if (SF.Ads.AdblockFallbackEnabled && SF.adblock) {
        $('#content-for-adblock').show();
        $('#content-fallback').hide();
    }
};


SF.Ads.showFallbackTemplate = function(){
    //the ads have already been written; just need to show it.
    $('#content-fallback').show();

    SF.Ads.pushTemplateImpressionBeacon(SF.Ads.FallbackTemplateName);
};

//Push a beacon to track ad template impression per pagetype, with geoloc data.
SF.Ads.pushTemplateImpressionBeacon = function(template)
{
  if (window.ga && SF.Ads.AdTemplateImpression && template) {
    var friendlyName = SF.Ads.friendlyPageName();
    ga('send', 'event', 'AdTemplateImpression_' + friendlyName, template, SF.geoCountryCode, 1, {'nonInteraction': 1});
  }
};

//Compose a friendly name for the page based on page ID in body tag
SF.Ads.friendlyPageName = function(){
  var pageID = $('body').attr('id');
  var friendlyName = '';
  switch (pageID) {
    case 'pg_dwnld':
      friendlyName = 'DownloadPage';
      break;
    case 'pg_postdownload':
      friendlyName = 'PostDownloadPage';
    break;
  }
  return friendlyName;
};

//Watch for leadgen resize message
//Also serves as general signal that leadgen served.
SF.Ads.watchLeadgenResize = function(customHandler)
{
    window.addEventListener('message', receiveMessage, false);
    function receiveMessage(evt){
        if (evt.data && evt.data.lf_iframeid && evt.data.lf_height) {
            //resize iframe to fit larger leadgen form
            document.getElementById(evt.data.lf_iframeid).height = (evt.data.lf_height) + "px";

            //Additional handler for presence of leadgen
            if (customHandler) {
                customHandler();
            }
        }
    }
};
