//###########
// Globals //
//###########

var gaShowCounter = {};
var gaVideosCounter = {};
var tnsVideosCounter = {};
var documentReferrer = document.referrer;


var _gaq = _gaq || [];
if (!Object.prototype.hasOwnProperty.call(window, '_PAGE_TYPE')) {
	var _PAGE_TYPE;
}


var tns_names_hash = {
     1:    "1",
     151340848: "1",
     2:	"2",
     155351581: "3",
     155463220:	"4",
     150097962:	"5",
     151328982: "2",
     165128674: "6",
     165128699: "7",
     165128714: "8",
     165128734: "9",
     165128752: "10",
     165128758: "11",
     205267009: "12"
   };


//############################################
// RIAN Media Player - TNS Plugin Callbacks //
//############################################

//

function PlayHeadTimer() {
	var self = this;
	this.bindPlayheadTime = function (vid) {
		this.videoWrp = vid;
		this.playheadTimer = setInterval(function(){
			self.onPlayheadTimeChange();
		}, 1000)
	}
	this.unBindPlayheadTime = function () {
		if (this.playheadTimer) clearInterval(this.playheadTimer);
	}

	this.onPlayheadTimeChange = function () {
		var th = $('#' + self.videoWrp),
			video = $('video', th),
			currentTime = video ? video[0].currentTime : 0,
			totalTime = video ? video[0].duration : 0;

		googleAnalyticsHTML5TimeHandler(currentTime,totalTime);
	}
}
var html5PlayHeadTimer = new PlayHeadTimer();

function isLoopChannel() {
	return (location.pathname == '/riatv/' && ( location.hash == '#loop' || location.hash == "") ) ||
		( location.pathname == '/' && (location.hostname == 'www.ria.ru' || location.hostname == 'ria.ru' ) )
}

function tnsLoad(mediaId){
	if(
		typeof(_gaq) != 'undefined' && typeof( _gaq.push ) == 'function' && !isLoopChannel()
	)
		_gaq.push(['_trackEvent', 'Player_load', location.href, document.referrer, 0, true]);

	tnsCounterSend('videoload', mediaId);
}


// Старт видео
function tnsStart(url, mediaId, sourceId){
	if( typeof(player) == 'undefined' )
		player = {};

	player.current_video = {
		"events"	:	{},
		"time"		:	{ "started" : (new Date()).getTime() }
	};

	googleAnalyticsStart(url, mediaId);
	tnsCounterStart(mediaId, sourceId);
    fbWatchStart(mediaId)
}



// Середина видео
function tnsMiddle(url, mediaId, sourceId){
	//googleAnalyticsMiddle(url, mediaId);
}



// Конец видео
function tnsComplete(url, mediaId, sourceId){
	googleAnalyticsComplete(url, mediaId);
	tnsCounterComplete(mediaId, sourceId);
    fbWatchEnd(mediaId)
}



// Время
function tnsTime(time, url, mediaId, sourceId){
	googleAnalyticsTime(time, url, mediaId);
}


//#########################
// HTML 5 VIDEO
// TNS Counter functions //
//#########################


function html5videoTNSFunctions(vid) {

	var self = this,
		th = $('#' + vid),
		video = $('video', th);

	video.bind('playing', function() {
		googleAnalyticsStart();
		if (html5PlayHeadTimer) html5PlayHeadTimer.bindPlayheadTime(vid);
	}).bind('ended', function() {
		googleAnalyticsComplete();
		if (html5PlayHeadTimer) html5PlayHeadTimer.unBindPlayHeadTime();
	});



}




//#########################
// TNS Counter functions //
//#########################


function tnsCounterStart(mediaId, sourceId){


	//var mb_img = new Image();
	//mb_img.src = 'http://local.mb.rian.ru/cgi-bin/banner/372?rian_local_random&login=video.control_pixel_video_start&rand='+Math.random(999999);

	tnsCounterSend('videostart', mediaId);

}




function tnsCounterComplete(mediaId, sourceId){

	var mb_img1 = new Image();
	mb_img1.src = 'http://local.mb.rian.ru/cgi-bin/banner/511?rian_local_random&login=video.control_pixel_video_finish&nocache=' + Math.round( Math.random() * 1000 );

	tnsCounterSend('videoend', mediaId);

}




function tnsCounterSend(event,  mediaId){
	if( typeof(tnsVideosCounter) != 'undefined' && typeof( tnsVideosCounter[mediaId] ) != 'undefined' && ( typeof( tnsVideosCounter[mediaId][event] ) == 'undefined' || typeof( tnsVideosCounter[mediaId][event]['fired'] ) == 'undefined' )  ){
		var img = new Image(),
			tns_postfix = ( typeof( tnsVideosCounter[mediaId]['postfix'] ) == "string" && tnsVideosCounter[mediaId]['postfix'] != '' ) ? tnsVideosCounter[mediaId]['postfix'] : 's' ;
		img.src = 'http://www.tns-counter.ru/V13b****rian_ru/ru/CP1251/tmsec='+tnsVideosCounter[mediaId]['tnsTypes'][0]+"-"+event+'-' + tns_postfix + '/?rand='+Math.random(999999);
		tnsVideosCounter[mediaId][event] = { "fired" : true };
	}
}


//##############################
// Google Analytics functions //
//##############################



function googleAnalyticsStart(url, mediaId){
	//googleAnalyticsSend('Start', url, mediaId);
	if( typeof(_gaq) != 'undefined' && typeof( _gaq.push ) == 'function' ){

		if (isLoopChannel()) {
			if (window._PAGE_TYPE && window._PAGE_TYPE == 'index') {
				_gaq.push(['_trackEvent', 'Video_block', 'Video_start', '/', 0, true]);
			}
			_gaq.push(['_trackEvent', 'Loop_start', location.href, document.referrer, 0, true]);
		} else {
			var url_node = document.getElementById("article-url"),
				article_url = ( url_node ) ? url_node.getAttribute("rel") : location.href,
				total_videolen_node = $('.video_info .videoLength'),
				total_videolen = ( total_videolen_node ) ? total_videolen_node.text() : '00:00:00';


			_gaq.push(['_trackEvent', 'Video_start', article_url, total_videolen, 0, true]);
		}
	}
}



/*function googleAnalyticsMiddle(url, mediaId){
	if (gaVideosCounter[mediaId] != 'Videocolumns') {
		googleAnalyticsSend('Middle', url, mediaId);
	}
}
*/

function googleAnalyticsComplete(url, mediaId){
    //googleAnalyticsSend('End', url, mediaId);
	if( typeof(_gaq) != 'undefined' && typeof( _gaq.push ) == 'function' ){

		if (!isLoopChannel()) {
			var url_node = document.getElementById("article-url"),
				article_url = ( url_node ) ? url_node.getAttribute("rel") : location.href;

			_gaq.push(['_trackEvent', 'Video_progress', article_url, '1', 0, true]);
			_gaq.push(['_trackEvent', 'Video_end', location.href, '100', 0, true]);
		}
	}
}



function googleAnalyticsTime(time, url, mediaId){
	if( typeof(_gaq) != 'undefined' && typeof( _gaq.push ) == 'function' ){

		var current_time_played =  Math.floor( ((new Date()).getTime() - player.current_video.time.started)/1000/60 );
		// GA stat for id 321141067 ( loop channel )
		// if( mediaId == '321141067' || MEDIAID == '321141067' ){
		if( isLoopChannel() ){

			if( current_time_played >= 1 && current_time_played < 2 && typeof(player.current_video.events.loop_1min) == 'undefined' ){
				_gaq.push(['_trackEvent', 'loop_1min', location.href, document.referrer ]);
				player.current_video.events.loop_1min = true
			}

			if( current_time_played >= 3 && current_time_played < 4 && typeof(player.current_video.events.loop_3min) == 'undefined'  ){
				_gaq.push(['_trackEvent', 'loop_3min', location.href, document.referrer ]);
				player.current_video.events.loop_3min = true
			}
		}

		// GA stat for video
		else{
			var	total_videolen_node = $('.video_info .videoLength')
				total_videolen = ( total_videolen_node ) ? total_videolen_node.attr('rel') : 0,
				progress_points = [ .25, .5, .75 ],
				progress_time_points = [
					total_videolen * .25,
					total_videolen * .5,
					total_videolen * .75,
					total_videolen * 1
				];

			for( var i = 0; i < progress_points.length; i++ ){
				if( time >= progress_time_points[i] && time < progress_time_points[i + 1] && typeof( player.current_video.events[ "progress" + progress_points[i] ] ) == 'undefined' ){
					_gaq.push(['_trackEvent', 'Video_progress', location.href, progress_points[i].toString(), 0, true]);
					player.current_video.events[ "progress" + progress_points[i] ] = true;
				}
			}

		}
	}
}


// HTML5 GA time handler

function googleAnalyticsHTML5TimeHandler(currentTime, duration){
	if( typeof(_gaq) != 'undefined' && typeof( _gaq.push ) == 'function'){

		var current_time_played =  Math.floor(currentTime / 60);
		// GA stat for id 321141067 ( loop channel )
		// if( mediaId == '321141067' || MEDIAID == '321141067' ){
		if( isLoopChannel() ){

			if( current_time_played >= 1 && current_time_played < 2){
				_gaq.push(['_trackEvent', 'loop_1min', location.href, document.referrer ]);

			}

			if( current_time_played >= 3 && current_time_played < 4){
				_gaq.push(['_trackEvent', 'loop_3min', location.href, document.referrer ]);
			}
		}

		// GA stat for video
		else{
			var	total_videolen = duration,
				progress_points = [ .25, .5, .75 ],
				progress_time_points = [
					total_videolen * .25,
					total_videolen * .5,
					total_videolen * .75,
					total_videolen * 1
				];

			for( var i = 0; i < progress_points.length; i++ ){
				if( currentTime >= progress_time_points[i] && currentTime < progress_time_points[i + 1] ){
					_gaq.push(['_trackEvent', 'Video_progress', location.href, progress_points[i].toString(), 0, true]);
				}
			}

		}
	}
}



// отправка в GA
function googleAnalyticsSend(action, url, mediaId){
    //var ur = processUrl(url.toString());
    _gaq.push(['_trackEvent', gaVideosCounter[mediaId], action, document.URL]);
    //_gaq.push(['_trackEvent', 'Video', action, document.URL]);
}



// преобразовать URL для точного отражения видео (хост + ID)
function processUrl(url){
	var str = url.replace(/(((%26)|&).*)/g, "");
    return str;
}


/*
function googleAnalyticsExecute(){

	if(GA){
		_gaq.push(['_setAccount', GA]);
		_gaq.push(['_trackPageview']);

		(function() {
		    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
		    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		})();
	}
	else if (console){
		console.error('Error! Variable GA is not defined!')
	}

}


googleAnalyticsExecute(); */



// fbVideo.watches

function fbWatchStart(url){

    if(typeof(document.facebook_userbar)!="undefined"){

        var object      =   document.facebook_userbar,
            dateTime    =   new Date(),
            url         =   ( document.getElementById("article-url").getAttribute("rel") )? document.getElementById("article-url").getAttribute("rel"):location.href;


        /*
         *if( object.methods.settings.get.apply( object, ["video-view-event"] ) == "true" && object.methods.settings.get.apply( object, ["enable_feed"] ) == "true" )
            object.methods.events.FB.actions.video.watches.apply( object, [ null, url, { "start_time": dateTime.toUTCString() } ])
        */
        object.methods.actions.video.watches.apply( object, [ url, { "start_time": dateTime.toUTCString() } ] );
    }

}

function fbWatchEnd(url){
    /*if(typeof(document.facebook_userbar)!="undefined"){

        var object  =   document.facebook_userbar,
            dateTime = new Date();

        if( object.methods.settings.get.apply( object, ["video-view-event"] ) == "true" && object.methods.settings.get.apply( object, ["enable_feed"] ) == "true" )
        object.methods.events.actions.video.modify.apply( object, [ object.settings.itemId[ "video" ], { "end_time": dateTime.toUTCString() } ])

    }*/
}

// bind unload or window close event for fb statistic ( end_time )
/*
if(typeof(document.social_bar)!="undefined")
    window.onunload = window.close = function(){
        var dateTime = new Date();
        document.social_bar.methods.events.actions.video.modify.apply(document.social_bar, [ document.social_bar.settings.itemId[ "video" ], { "end_time": dateTime.toUTCString() } ])
    }*/