ortense
5/6/2014 - 8:10 PM

Google Analytics Track Youtube Interactions

Google Analytics Track Youtube Interactions

do (window, document) ->

	iframes = document.getElementsByTagName("iframe")
	youTubeIframes = []
	regex = /.*youtube.*\/(embed|v)\/(.+)\?.*/

	window.youtube = window.youtube or {}
	youtube.movies = youtube.movies or {}

	category = youtube.movies.category = if youtube.movies.category then youtube.movies.category else "youtube"
	range = youtube.movies.timeRange = if youtube.movies.timeRange then youtube.movies.timeRange else [25, 50, 75]
	
	myYT = 
		mapPercent: {}

		forceApi: (iframe) ->
			src = iframe.src
			if src.indexOf(".youtube.com") > -1 #se o iframe é do youtube
				if src.indexOf("enablejsapi=1") is -1 #se a api não esta ligada
					if src.indexOf("?") is -1
						iframe.src = src = src + "?enablejsapi=1" #força a api
					else
						iframe.src = src = src + "&enablejsapi=1" #força a api
				
				videoId = src.match(regex)[2]
				div = document.createElement("div") #cria um div
				div.id = videoId #id do div é igual ao id do video
				iframe.parentNode.insertBefore(div, iframe) #insere o div abaixo do iframe
				div.appendChild(iframe) #move o iframe para dentro do novo div
				youTubeIframes.push(iframe)

		startPercent: (target) ->
			url = target.getVideoUrl()
			that = myYT.mapPercent[url] = {}

			that.count = if that.count then that.count else 0
			that.last = if that.last then that.last else 0
			
			that.duration = parseInt(target.getDuration(), 10)

			calc = ->
				current = target.getCurrentTime()
				percent = (100 * current) / that.duration
				if percent >= range[that.count]

					that.last = range[that.count]

					if window._gaq
						_gaq.push ["_trackEvent", category, "#{that.last}%", url]
					if window.ga
						ga("send", "event", category, "#{that.last}%", url)
					if window._gas
						_gas.push ["_trackEvent", category, "#{that.last}%", url]

					that.count = that.count + 1

			that.timer = window.setInterval(calc, 1000)

		stopPercent: (target) ->
			window.clearTimeout(myYT.mapPercent[target.getVideoUrl()].timer)

		trackAction: (action, target) ->
			videoUrl = target.getVideoUrl()
			if window._gaq
				_gaq.push ["_trackEvent", category, action, videoUrl]
			if window.ga
				ga("send", "event", category, action, videoUrl)
			if window._gas
				_gas.push ["_trackEvent", category, action, videoUrl]

		stageChange: (event) ->
			target = event.target
			that = myYT.mapPercent[target.getVideoUrl()]
			switch event.data
				when 0
					myYT.trackAction "finish", target
					myYT.stopPercent target
					that.count = 0
				when 1
					myYT.trackAction "play", target
					myYT.startPercent target
				when 2
					myYT.trackAction "pause", target
					myYT.stopPercent target
				when 3
					myYT.trackAction "buffering", target

		playerReady: (event) ->
			myYT.trackAction "ready", event.target

	window.onYouTubePlayerAPIReady = ->
		category = youtube.movies.category = if youtube.movies.category then youtube.movies.category else "youtube"

		myYT.forceApi(iframe) for iframe in iframes
		youtube.movies.player = {}

		for iframe in youTubeIframes
			opts =
				videoId: iframe.parentNode.id
				height: iframe.height
				width: iframe.width

			player = new YT.Player(iframe.parentNode, opts)
			player.addEventListener("onStateChange", myYT.stageChange)
			player.addEventListener("onReady", myYT.playerReady)
			youtube.movies.player[opts.videoId] = player

	# carregando api externa do youtube
	firstScriptTag = document.getElementsByTagName('script')[0]
	youtubeApi = document.createElement("script")

	youtubeApi.src = "//www.youtube.com/iframe_api"
	firstScriptTag.parentNode.insertBefore(youtubeApi, firstScriptTag)