Source: OnSiteAds/onsiteads.js

/**
 * @class
 * @classdesc Plugin used to manage publisher and self-promotion.
 * @name OnSiteAds
 * @memberof ATInternet.Tracker.Plugins
 * @type {function}
 * @param parent {object} Instance of the Tag used
 * @public
 */
window['ATInternet']['Tracker']['Plugins']['OnSiteAds'] = function (parent) {
    "use strict";
    var self = this;

    // Plugin's dependencies
    var _dependencies = ['Utils', 'TechClicks'];
    // Current url
    var _href = "";

    /**
     * Get page label with chapters
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param tagObject {object} page context
     * @return string {string} Page name completed with chapters (all from page context)
     * @private
     */
    var _getFullName = function (tagObject) {
        var name = tagObject['name'];
        parent['exec']('Utils', 'manageChapters', [tagObject, 'chapter', 3], function (data) {
            name = data + (name ? name : '');
        });
        return name;
    };

    /**
     * Get a property in an object
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param object {object} object to use
     * @param key {string} key wanted
     * @return string {*} Either the value otherwise an empty string
     * @private
     */
    var _getProperty = function (object, key) {
        return (object[key] ? object[key] : '');
    };

    /**
     * Build a Publisher or Self-Promotion campaign (based on tag data)
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param tagObject {object} tag object
     * @param clickOrImpression {string} key indicating which object is to process (either a "click" or an "impression")
     * @return string {string} Campaign formatted depending on tag data
     * @private
     */
    var _buildCampaign = function (tagObject, clickOrImpression) {
        var campaign = _getProperty(tagObject, clickOrImpression);
        if (campaign) {
            var prefix = _getProperty(tagObject, 'prefix');
            if (campaign['campaignId']) { // publisher
                prefix = prefix || 'PUB';
                var campaignId = _getProperty(campaign, 'campaignId'),
                    creation = _getProperty(campaign, 'creation'),
                    variant = _getProperty(campaign, 'variant'),
                    formatPublisher = _getProperty(campaign, 'format'),
                    generalPlacement = _getProperty(campaign, 'generalPlacement'),
                    detailedPlacement = _getProperty(campaign, 'detailedPlacement'),
                    advertiserId = _getProperty(campaign, 'advertiserId'),
                    url = _getProperty(campaign, 'url');
                return prefix + '-' + campaignId + '-' + creation + '-' + variant + '-' + formatPublisher + '-' + generalPlacement + '-' + detailedPlacement + '-' + advertiserId + '-' + url;
            } else if (campaign['adId']) { // selfpromotion
                prefix = prefix || 'INT';
                var adId = _getProperty(campaign, 'adId'),
                    formatSelfPromotion = _getProperty(campaign, 'format'),
                    productId = _getProperty(campaign, 'productId');
                return prefix + '-' + adId + '-' + formatSelfPromotion + '||' + productId;
            }
        }
    };

    /**
     * Send an individual campaign's click hit (hiType is "onSiteAdsClick")
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param tagObject {object} tag object
     * @private
     */
    var _sendClick = function (tagObject) {
        var contextPageObject = parent['getContext']('page') || {};
        parent.sendHit({
            atc: _buildCampaign(tagObject, 'click'),
            type: 'AT',
            patc: _getFullName(contextPageObject),
            s2atc: contextPageObject['level2'] || '',
            stc: tagObject['customObject'] || ''
        }, [['hitType', ['onSiteAdsClick']]]);
    };

    /**
     * Send an individual campaign's impression hit (hiType is "onSiteAdsImpression")
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param tagObject {object} tag object
     * @private
     */
    var _sendImpression = function (tagObject) {
        parent.sendHit({
            ati: _buildCampaign(tagObject, 'impression'),
            type: 'AT',
            stc: tagObject['customObject'] || ''
        }, [['hitType', ['onSiteAdsImpression']]]);
    };

    /**
     * Push a new impression's campaign to be sent at dispatch
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param campaignValue {object} campaign
     * @param hitType {object} Either "selfPromotion" or "publisher"
     * @private
     */
    var _pushImpression = function (campaignValue, hitType) {
        var ati = parent.buffer.get("ati", true) || {};
        if (typeof ati['value'] === 'string') {
            ati['value'] = [ati['value']];
        } else {
            ati['value'] = ati['value'] || [];
        }
        ati['options'] = ati['options'] || {hitType: [hitType, 'page']};
        ati['value'].push(campaignValue);
        parent.buffer.set("ati", ati['value'], ati['options']);
    };

    /**
     * Set a campaign for a futur dispatch
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param tagObject {object} tag object
     * @param hitType {object} Either "selfPromotion" or "publisher"
     * @private
     */
    var _simpleSet = function (tagObject, hitType) {
        if (tagObject['click']) {
            parent.setParam("atc", _buildCampaign(tagObject, 'click'), {hitType: [hitType, 'page']});
        } else if (tagObject['impression']) {
            parent.setParam("ati", _buildCampaign(tagObject, 'impression'), {hitType: [hitType, 'page']});
        }
        if (tagObject['customObject']) {
            parent['setContext']('onsiteads', {customObject: tagObject['customObject']});
            var contextPageObject = parent.getContext('page') || {};
            contextPageObject.customObject = ATInternet.Utils.completeFstLevelObj(contextPageObject.customObject, tagObject['customObject'], false);
            parent.setContext('page', contextPageObject);
        }
        parent.dispatchSubscribe('onSiteAds');
    };

    //Définition des helpers
    /**
     * [Object added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Tags for self-promotion campaigns
     * @name selfPromotion
     * @memberof ATInternet.Tracker.Tag
     * @inner
     * @type {object}
     * @property {function} set Tag helper, see details here {@link ATInternet.Tracker.Tag#selfPromotion.set}
     * @property {function} add Tag helper, see details here {@link ATInternet.Tracker.Tag#selfPromotion.add}
     * @property {function} send Tag helper, see details here {@link ATInternet.Tracker.Tag#selfPromotion.send}
     * @public
     */
    parent["selfPromotion"] = self['selfPromotion'] = {};

    /**
     * [Object added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Tags for publisher campaigns
     * @name publisher
     * @memberof ATInternet.Tracker.Tag
     * @inner
     * @type {object}
     * @property {function} set Tag helper, see details here {@link ATInternet.Tracker.Tag#publisher.set}
     * @property {function} add Tag helper, see details here {@link ATInternet.Tracker.Tag#publisher.add}
     * @property {function} send Tag helper, see details here {@link ATInternet.Tracker.Tag#publisher.send}
     * @public
     */
    parent["publisher"] = self['publisher'] = {};

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Tagging method for publisher campaigns, to be used with the tag.dispatch() method
     * @alias publisher.set
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @param tagObject {object} tagObject must contain a property 'click' or 'impression', you can force a specific prefix with a property 'prefix'
     * @example
     * <pre><code class="javascript">tag.publisher.set({
     *      impression:{
     *          campaignId : 'id[label]',
     *          creation : 'id[label]',
     *          variant : 'id[label]',
     *          format : '[120x40]',
     *          generalPlacement : '[label]',
     *          detailedPlacement : 'id[label]',
     *          advertiserId : 'id[label]',
     *          url : '[urlEncoded]'
     *      }
     * });
     * tag.dispatch();
     * </code></pre>
     * This will send a self-promotion campaign like : &atc=PUB-id[campaignId]-id[creation]-id[variant]-id-[generalPlacement]-[detailedPlacement]-id[advertiserId]-urlencoded
     * @public
     */
    parent["publisher"]['set'] = self['publisher']['set'] = function (tagObject) {
        _simpleSet(tagObject, 'publisher');
        /* @if debug */
        parent.debug('OnSiteAds:publisher:set', 'DEBUG', 'method ended', tagObject);
        /* @endif */
    };

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Tagging method for self-promotion campaigns, to be used with the tag.dispatch() method
     * @alias selfPromotion.set
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @param tagObject {object} tagObject must contain a property 'click' or 'impression', you can force a specific prefix with a property 'prefix'
     * @example
     * <pre><code class="javascript">tag.selfPromotion.set({
     *     impression : {
     *         adId : 'integer',
     *         format : 'id[format]',
     *         productId : 'productId'
     *     }
     * });
     * tag.dispatch();
     * </code></pre>
     * This will send a self-promotion campaign like : &ati=INT-integer-id[format]||productId
     * <pre><code class="javascript">tag.selfPromotion.set({
     *     click : {
     *         adId : 'integer',
     *         format : 'id[format]',
     *         productId : 'productId'
     *     }
     * });
     * tag.dispatch();
     * </code></pre>
     * This will send a self-promotion campaign like : &atc=INT-integer-id[format]||productId
     * <pre><code class="javascript">tag.selfPromotion.set({
     *     click : {
     *         adId : 'integer',
     *         format : 'id[format]',
     *         productId : 'productId'
     *     },
     *     prefix : 'VALUE',
     *     customObject:{one:1,two:2}
     * });
     * tag.dispatch();
     * </code></pre>
     * This will send a self-promotion campaign like : &atc=VALUE-integer-id[format]||productId
     * @public
     */
    parent["selfPromotion"]['set'] = self['selfPromotion']['set'] = function (tagObject) {
        _simpleSet(tagObject, 'selfPromotion');
        /* @if debug */
        parent.debug('OnSiteAds:selfPromotion:set', 'DEBUG', 'method ended', tagObject);
        /* @endif */
    };

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Tagging method for publisher campaigns, allow to cumulate campaigns to be sent with the tag.dispatch() method
     * @alias publisher.add
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @param tagObject {object} tagObject must contain a property 'click' or 'impression', you can force a specific prefix with a property 'prefix'
     * @example
     * <pre><code class="javascript">tag.publisher.add({
     *      impression:{
     *          campaignId : 'id[label]',
     *          creation : 'id[label]',
     *          variant : 'id[label]',
     *          format : '[120x40]',
     *          generalPlacement : '[label]',
     *          detailedPlacement : 'id[label]',
     *          advertiserId : 'id[label]',
     *          url : '[urlEncoded]'
     *      }
     * });
     * tag.publisher.add({
     *      impression:{
     *          campaignId : 'id2[label2]',
     *          creation : 'id2[label2]',
     *          variant : 'id2[label2]',
     *          format : '[60x40]',
     *          generalPlacement : '[label2]',
     *          detailedPlacement : 'id2[label2]',
     *          advertiserId : 'id2[label2]',
     *          url : '[urlEncoded2]'
     *      }
     * });
     * tag.dispatch();
     * </code></pre>
     * This will send a self-promotion campaign like : &atc=PUB-id[campaignId]-id[creation]-id[variant]-id-[generalPlacement]-[detailedPlacement]-id[advertiserId]-urlencoded
     * @public
     */
    parent["publisher"]['add'] = self['publisher']['add'] = function (tagObject) {
        _pushImpression(_buildCampaign(tagObject, 'impression'), 'publisher');
        parent.dispatchSubscribe('onSiteAds');
        /* @if debug */
        parent.debug('OnSiteAds:publisher:add', 'DEBUG', 'method ended', tagObject);
        /* @endif */

    };

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Tagging method for self-promotion campaigns, allow to cumulate campaigns to be sent with the tag.dispatch() method
     * @alias selfPromotion.add
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @param tagObject {object} tagObject must contain a property 'click' or 'impression', you can force a specific prefix with a property 'prefix'
     * @example
     * <pre><code class="javascript">tag.selfPromotion.add({
     *     impression : {
     *         adId : 'integer',
     *         format : 'id[format]',
     *         productId : 'productId'
     *     }
     * });
     * tag.selfPromotion.add({
     *     impression : {
     *         adId : 'integer2',
     *         format : 'id2[format2]',
     *         productId : 'productId2'
     *     }
     * });
     * tag.dispatch();
     * </code></pre>
     * This will send a self-promotion campaign like : &ati=INT-integer-id[format]||productId,INT-integer2-id2[format2]||productId2
     * @public
     */
    parent["selfPromotion"]['add'] = self['selfPromotion']['add'] = function (tagObject) {
        _pushImpression(_buildCampaign(tagObject, 'impression'), 'selfPromotion');
        parent.dispatchSubscribe('onSiteAds');
        /* @if debug */
        parent.debug('OnSiteAds:selfPromotion:add', 'DEBUG', 'method ended', tagObject);
        /* @endif */
    };

    /**
     * Generic method to send self-promotion or publisher campaigns.
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @param tagObject {object} tagObject should contain the campaign object, optionally a "customObject" and a "elem"(HTMLElement, to manage redirections)
     * @private
     */
    var _advertEvent = self["advertEvent"] = function (tagObject) {
        var resultCheck = true;
        // check if the clicked element should be managed and return false if it is the case, manageClick also adds the callback process if needed
        parent['exec']('TechClicks', 'manageClick', [tagObject['elem'], tagObject['event'], tagObject['callback']], function (data) {
            resultCheck = data;
        });
        if (tagObject['click']) {
            _sendClick(tagObject);
        } else if (tagObject['impression']) {
            _sendImpression(tagObject);
        }
        return resultCheck;
    };

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Alternative tagging method for publisher campaigns. This method manages redirections on click if necessary
     * @alias publisher.send
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @param tagObject {object} The campaign , you can add a "customObject" property, and an "elem" property to manage redirection
     * @example
     * <pre><code class="html">&lt;a href="..." onclick="return tag.publisher.send({elem:this,click:{campaignId:'id[label]',creation:'id[label]',variant:'id[label]',format:'[120x40]',generalPlacement:'[label]',detailedPlacement:'id[label]',advertiserId:'id[label]',url:'[urlEncoded]'}});"&gt;Pub&lt;/a&gt;
     * </code></pre>
     * @public
     */
    parent["publisher"]['send'] = self['publisher']['send'] = function (tagObject) {
        /* @if debug */
        parent.debug('OnSiteAds:publisher:send', 'DEBUG', 'method started', tagObject);
        /* @endif */
        return _advertEvent(tagObject);
    };

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Alternative tagging method for self-promotion campaigns. This method manages redirections on click if necessary
     * @alias selfPromotion.send
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @param tagObject {object} The campaign , you can add a "customObject" property, and an "elem" property to manage redirection
     * @example
     * <pre><code class="html">&lt;a href="..." onclick="return tag.selfPromotion.send({elem:this,click:{adId:'id',format:'[120x40]',productId:'id'}});"&gt;Pub&lt;/a&gt;
     * </code></pre>
     * @public
     */
    parent["selfPromotion"]['send'] = self['selfPromotion']['send'] = function (tagObject) {
        /* @if debug */
        parent.debug('OnSiteAds:selfPromotion:send', 'DEBUG', 'method started', tagObject);
        /* @endif */
        return _advertEvent(tagObject);
    };

    //'OnSitesAds' est le helper commun aux quatre définis avant.
    //Il permet de définir une seule méthode 'send' pour les quatre.
    /**
     * [Object added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Tags for campaigns
     * @name onSiteAds
     * @memberof ATInternet.Tracker.Tag
     * @inner
     * @type {object}
     * @private
     */
    parent["onSiteAds"] = {};

    /**
     * [Helper added by plugin {@link ATInternet.Tracker.Plugins.OnSiteAds OnSiteAds}] Will be called by tracker.dispatch if any self-promotion/publisher set/add has been called
     * @alias onSiteAds.onDispatch
     * @memberof! ATInternet.Tracker.Tag#
     * @function
     * @private
     */
    parent["onSiteAds"]['onDispatch'] = self['onDispatch'] = function () {
        if (!parent.dispatchSubscribed('page')) {
            var contextPageObject = parent['getContext']('page') || {};
            parent['setParam']('type', 'AT', {hitType: ['publisher', 'selfPromotion']});
            if (parent['getParam']('atc')) {
                parent['setParam']('patc', _getFullName(contextPageObject), {hitType: ['publisher', 'selfPromotion']});
                parent['setParam']('s2atc', contextPageObject['level2'] || '', {hitType: ['publisher', 'selfPromotion']});
            }
            var contextOnSiteAds = parent['getContext']('onsiteads');
            if (contextOnSiteAds && contextOnSiteAds.customObject) {
                parent['setParam']('stc', contextOnSiteAds.customObject, {
                    encode: true,
                    hitType: ['publisher', 'selfPromotion']
                });
            }
            parent['sendHit'](null, [['hitType', ['publisher', 'selfPromotion']]]);
        }
    };

    /**
     * Run process.
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @private
     */
    var _run = function () {
        _href = document.location.href;
        parent['plugins']['exec']('Utils', 'getQueryStringValue', ['xtatc', _href], function (data) {
            if (data) {
                parent.setParam("atc", data, {hitType: ['publisher', 'selfPromotion', 'page']});
            }
        });
        parent.emit('OnSiteAds:Ready', {
            lvl: 'INFO',
            details: {
                href: _href
            }
        });
    };

    /**
     * Initialize plugin.
     * @memberof ATInternet.Tracker.Plugins.OnSiteAds#
     * @function
     * @private
     */
    var _init = function () {
        parent['plugins']['waitForDependencies'](_dependencies, _run);
    };

    _init();

    /* @if test */
    self['_sendClick'] = _sendClick;
    self['_sendImpression'] = _sendImpression;
    /* @endif */
};
window['ATInternet']['Tracker']['addPlugin']('OnSiteAds');