(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-42817937-2', 'auto');

function trackYoutube(categoria, iframes) {
var opt_config = {
    force: true,
    category: categoria, 
    percentages: [1, 5, 10, 25, 50, 75, 90]
};

/**
 * Array of percentage to fire events.
 */
var timeTriggers = opt_config.percentages;

/**
 * Used to map each vid to a set of timeTriggers and it's pool timer
 */
var poolMaps = {};

function pool(target, hash) {
    var time = target.getCurrentTime();
    
    if (poolMaps[hash] === undefined ||
        poolMaps[hash].timeTriggers.length <= 0) {
        return false;
    }
    var p = time / target.getDuration() * 100;
    if (p >= poolMaps[hash].timeTriggers[0]) {
        var action = poolMaps[hash].timeTriggers.shift();
        // Event
        ga('send', 'event', opt_config.category, 'show ' + action + '%', target.getVideoData().title);                
    }
    poolMaps[hash].timer = setTimeout(pool, 1000, target, hash);
}

function stopPool(target) {
  try{
    var h = target.getVideoData().title;
  }catch(e){
    console.log("stoppool");
  }
    if (poolMaps[h] && poolMaps[h].timer) {
        pool(target, h); // Pool one last time before clearing it.
        clearTimeout(poolMaps[h].timer);
    }
}

function startPool(target) {
    if (timeTriggers && timeTriggers.length) {
        var h = target.getVideoData().title;
        if (poolMaps[h]) {
            stopPool(target);
        } else {
            poolMaps[h] = {};
            poolMaps[h].timeTriggers = Array.prototype.slice.call(timeTriggers);
        }
        poolMaps[h].timer = setTimeout(pool, 1000, target, h);
    }
}

/**
 * Called when the Video State changes
 *
 * We are currently tracking only finish, play and pause events
 *
 * @param {Object} event the event passed by the YT api.
 */
var states = {};

function youtubeStateChange(event) {
    var time = event.target.getCurrentTime();
    var stateHandler = states[event.data];
    var action;

    if (typeof stateHandler === 'function') {
        //Se o evento de "play" tiver ocorrido muito próximo do início, considerá-lo "start"
        action = stateHandler(event.target) === 'play' && time < 0.5 ? 'start' : stateHandler(event.target);
    }
    if (action) {
    	ga('send', 'event', opt_config.category, action, event.target.getVideoData().title);                
    }
}

/**
 * Called when the player fires an Error Event
 *
 * @param {Object} event the event passed by the YT api.
 */
function youtubeError(event) {
		ga('send', 'event', opt_config.category, 'error (' + event.data + ')', event.target.getVideoData().title);
}

/**
 * Triggers the YouTube Tracking on the page
 *
 * Only works for the iframe tag. The video must have the parameter
 * enablejsapi=1 on the url in order to make the tracking work.
 *
 * @param {(object)} opts.
 */
function universalTrackYoutube(opts) {
    var force = opts.force;
    var youtube_videos = [];
    var firstTag, script, i;
    for (i = 0; i < iframes.length; i++) {
        if (iframes[i].src.indexOf('youtube.com/embed') >= 0) {
            iframes[i].src = iframes[i].src.replace("http:", "https:").replace("//youtube", "//www.youtube");
            if (iframes[i].src.indexOf('enablejsapi=1') === -1) {
                if (force) {
                    // Reload the video enabling the api
                    if (iframes[i].src.indexOf('?') === -1) {
                        iframes[i].src += '?enablejsapi=1';
                    } else {
                        iframes[i].src += '&enablejsapi=1';
                    }
                } else {
                    // We can't track players that don't have api enabled.
                    continue;
                }
            }
            youtube_videos.push(iframes[i]);
        }
    }
    if (youtube_videos.length > 0) {
        // this function will be called when the youtube api loads
        window.onYouTubeIframeAPIReady = function (youtube_videos_api, p, i) {
            states[YT.PlayerState.ENDED] = function (event) {
                stopPool(event);
                return 'finish';
            };
            states[YT.PlayerState.PLAYING] = function (event) {
                startPool(event);
                return 'play';
            };
            states[YT.PlayerState.PAUSED] = function (event) {
                stopPool(event);
                return 'pause';
            };
            states[YT.PlayerState.BUFFERING] = function (event) {
                return null;
            };
            states[YT.PlayerState.CUED] = function (event) {
                return null;
            };
            if (!youtube_videos_api) {
                
                for (i = 0; i < youtube_videos.length; i++) {
                    p = new YT.Player(youtube_videos[i]);
                    p.addEventListener('onStateChange', youtubeStateChange);
                    p.addEventListener('onError', youtubeError);
                    p = null;
                }
            } 
            else if (youtube_videos_api) {
                for (i = 0; i < youtube_videos_api.length; i++) {
                    p = null;
                    p = new YT.Player(youtube_videos_api[i]);
                    p.addEventListener('onStateChange', youtubeStateChange);
                    p.addEventListener('onError', youtubeError);
                    p = null;
                }
            }
        };
    }
    if (window.YT && youtube_videos && youtube_videos.length > 0) {
        onYouTubeIframeAPIReady(youtube_videos);
    }
    else {
        var script = document.createElement('script');
        script.src = 'https://www.youtube.com/iframe_api';
        script.type = 'text/javascript';
        script.async = true;
        var firstScript = document.getElementsByTagName('script')[0];
        firstScript.parentNode.insertBefore(script, firstScript);
    }

}
universalTrackYoutube(opt_config);
}

//ao carregar a página
var iframes = document.getElementsByTagName('iframe');
trackYoutube("Conteúdo - Produto", iframes);


