var AdTimeout;
var RunningAd	= 0;
var RunningTV	= 0;
var LastTVSize	= 0;

var Cat;
var Id;
var Naam;
var Player;
var Wmp;
var Timer1;
var OpenTVtimer;
var OpenTVdelayCounter = 0;

// Player: 0 = let the PC decide...
//         1 = Windows Media Player
//         2 = JW WMV Player
//         3 = JW Player
function OpenStream(categorie, id, naam, player, staticPlayer, Ratio_)
{
	clearTimeout( Timer1 );
	
	if( Player != player ) {
		clearTimeout( OpenTVtimer );
	}

	// Sla op welke zender het is (voor help)
	$('#CurZenderID').val( id );
	$('#CurZenderName').val( categorie + ' - ' + naam );

	Cat		= categorie;
	Id		= id;
	Naam	= naam;
	Player	= player;
	Wmp		= staticPlayer;
	ScreenRatio = Ratio_;
	OpenTVdelayCounter = 0;

	// Zender URL maken
	getURL( )

	LastTVSize = 0;
	if( horizontalSlider.getValue() )
	{
		LastTVSize = horizontalSlider.getValue();
	}

	horizontalSlider.setValue(0);
	resizeTV( 1 );
	RunningTV = 0;
	// Empty TV screen
	$('#DirectURL').html('');

	// Naam v/h programma (reclame) opvragen
	getName( 1 );
	if( RunningAd == 0 )
		OpenReclame();
}

function OpenReclame()
{
	$('#TV').html('');
	$('#VideoStrip').html('');
	$('#TV').hide();
	$('#VideoStrip').show();
	// Make sure the screen isn't too small!

	// Dont start multiple ads at the same time please
	RunningAd = 1;

	// Clear the window for some advertisement
	$('#vs_a2s_tag_fullsize').html('');
	$('#Webspeciaal_Banner').html('');
	if( PreRollTimeOut > 0)
	{
		AdTimeout = setTimeout('PreloaderCallbackAfter("NOAD")', PreRollTimeOut);
		// Include Videostrip.com
		videostrip.PlayerPlacer.changeVideo('VideoStrip', Cnti_Key, Play_Key, 320, 270, true)
	} else {
		$('#VideoStrip').hide();
		$('#TV').show();
		OpenReclameKTO();
	}
}

function PreloaderCallbackOnStart( )
{
	clearTimeout( AdTimeout );
}

function PreloaderCallbackAfter( Ad ) {
	clearTimeout( AdTimeout );
	$('#VideoStrip').hide();
	$('#TV').show();
	if ( Ad == 'NOAD' ) {
		KTOreclame = 1;
	} else {
		KTOreclame = 0;
	}
	OpenReclameKTO()
}

function OpenReclameKTO()
{
	if( KTOreclame == 0 )
	{
		// Timeout is needed, to clean up Videostrip, b4 continueing!
		OpenTVtimer = setTimeout("OpenTV()", 500);
	} else {
		OpenReclameBanner();
		$.ajax({
			url: AbsLINK + "include/Ajax.GetAdd.php?categorie=" + Categorie,
			cache: false,
			dataType: 'html',
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$("#TV").html( '5. Error occurred while retrieving information<br />' + errorThrown + ' / ' + textStatus + ' / ' + errorThrown );
			},
			success: function( data, textStatus, XMLHttpRequest ) {
				$("#TV").html( data );
			}
		});

		OpenTVtimer = setTimeout("OpenTV()", 9000);
	}
}

function OpenReclameBanner() {
	$.ajax({
		url: AbsLINK + "include/Ajax.GetBanner.php",
		cache: false,
		dataType: 'html',
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$("#Webspeciaal_Banner").html( '6. Error occurred while retrieving information<br />' + errorThrown + ' / ' + textStatus + ' / ' + errorThrown );
		},
		success: function( data, textStatus, XMLHttpRequest ) {
			$("#Webspeciaal_Banner").html( data );
		}
	});
}

// Player: 0 = let the PC decide...
//         1 = Windows Media Player
//         2 = JW WMV Player
//         3 = JW Player
function OpenTV()
{
	Timer1 = setTimeout('SendTime(0.5)', (990 * 1 * 30) );

	RunningTV = 1;
	RunningAd = 0;
	horizontalSlider.setValue( LastTVSize );

// Workaround if JWPlayer wont disappear.
//	if( useJWplayer == true ) {
//		if( jwplayer("TV").getState() ) { jwplayer("TV").remove() }
//	}

	// If the is no URL to play, be patient and try again.
	if( $('#URLlink').val( ) == '' ) {
		OpenTVdelayCounter++;
		if( OpenTVdelayCounter < 51 ) // max: 5 sec wachten...
			setTimeout( 'OpenTV();', 100 );
		else
			alert('De zender kon tijdelijk niet geladen worden. Probeert u het nogmaals door op de zender te klikken.');
		return;
	}
	// Resize the TV to the proper ratio.
	resizeTV();

	if( Player == 0 )
	{
		// Allow the browser to decise what player to use.
		if ( !isSilverlightInstalled() )
		{
				pageTracker._trackPageview( '/API/Open/JWWMV/' + Cat + '/' + Naam + '(' + Id + ')' );
			Player = 1;
			CreateWMP( );
		}else{
				pageTracker._trackPageview( '/API/Open/WMP/' + Cat + '/' + Naam + '(' + Id + ')' );
			Player = 2;
			CreateJWWMV( );
		}

	}else if( Player == 1 ) { // Windows Media Player
		pageTracker._trackPageview( '/API/Static/WMP/' + Cat + '/' + Naam + '(' + Id + ')' );
		CreateWMP( )

	} else if( Player == 2 ) { // JW WMV Player
		pageTracker._trackPageview( '/API/Static/JWWMV/' + Cat + '/' + Naam + '(' + Id + ')' );
		CreateJWWMV( );

	} else if( Player == 3 ) { // JW Player
		pageTracker._trackPageview( '/API/Static/JWP/' + Cat + '/' + Naam + '(' + Id + ')' );
		CreateJWplayer( )
}	}

function setDirectURL( )
{
 	// Naam v/h programma opvragen (geen reclame)
 	getName( 0 )

	if( Naam == '' || Naam == false ) {
		Naam = '000';
	}

	var URL = AbsLINK + 'zenders/' + Cat + '/' + Id + '/' + Naam.replace('/', '--'); // + '/1/';
	$('#DirectURL').html( '<br />'+DirectURLtext+'<br /><input type="text" id="SelectAll" value="'+URL+'" onClick="SelectAll(this.id);"><br /><br />' );
}

function CreateWMP( )
{
	// Player cannot noy be zero! Therefor setDirectURL cannot not be in OpenTV.
	setDirectURL( );

	$("#TV").html( '' );
	$.ajax({
		url: AbsLINK + "include/Ajax.Wmp.php?id=" + Id + "&amp;brow=" + BrowserDetect.browser,
		dataType: 'html',
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$("#TV").html( '7. Error occurred while retrieving information<br />' + errorThrown + ' / ' + textStatus + ' / ' + errorThrown );
		},
		success: function( data, textStatus, XMLHttpRequest ) {
			$("#TV").html( data );
		}
	});

  setTimeout("resizeTV()", 100);
  setTimeout("resizeTV()", 1500);
}

function CreateJWWMV( )
{
	// Player cannot be zero! Therefor setDirectURL cannot be in OpenTV.
	setDirectURL( );

	$("#TV").html( '' );
	var cnt = document.getElementById('TV');
	var src = AbsLINK+'include/wmvplayer.xaml';
	var cfg = {
		file: $('#URLlink').val( ),
		height: '100%',
		width: '100%',
		volume: '70',
		autostart: 'true'
	};
	ply = new jeroenwijering.Player(cnt,src,cfg);	
}

function CreateJWplayer( )
{
	// Player cannot noy be zero! Therefor setDirectURL cannot not be in OpenTV.
	setDirectURL( );

	$("#TV").html( '' );
	$("<div/>", { id: "TV2" }).appendTo("#TV");

	jwplayer("TV2").setup( {
		allowscriptaccess: 'always',
		allowfullscreen: 'true',
		provider: 'http',
		stretching: 'exactfit',
		file: $('#URLlink').val( ),
		players: [
			{ type: "html5" },
			{ type: "flash", src: AbsLINK+"plugins/jwplayer/player.swf" }
		],
		height: '100%',
		width: '100%',
		volume: 70,
		autostart: true
	});
	jwplayer("TV2").onReady( function() {
		makeOuterHtml();
	});
	jwplayer("TV2").onComplete( function() {
		TVonComplete();
	});
}

function TVonComplete()
{
	// Resize the TV to the AD ratio.
	resizeTV( 1 );
	$("#TV").html( '<img src="'+ AbsLINK +'images/TVbox/tvholder.png" alt="KijkTvOnline.nl" width="100%" align="middle" />' );
}
// Work around, to make "remove" function in JWplayer, work for FF.
var _emptyTags = {
"IMG": true,
"BR": true,
"INPUT": true,
"META": true,
"LINK": true,
"PARAM": true,
"HR": true
};

function makeOuterHtml( ) {
if(typeof(HTMLElement) != 'undefined') { // prevents IE from seeing the rest
HTMLElement.prototype.__defineGetter__("outerHTML", function () {
var attrs = this.attributes;
var str = "<" + this.tagName;
for (var i = 0; i < attrs.length; i++)
str += " " + attrs[i].name + "=\"" + attrs[i].value + "\"";

if (_emptyTags[this.tagName])
return str + ">";

return str + ">" + this.innerHTML + "</" + this.tagName + ">";
});
HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var df = r.createContextualFragment(sHTML);
this.parentNode.replaceChild(df, this);
});
}
}
// End of the workaround.

function getURL( )
{
	// Reset the current URL.
	$('#URLlink').val( '' );
	$.ajax({
		url: AbsLINK + "include/Ajax.GetURL.php?id=" + Id,
		cache: false,
		dataType: 'html',
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$("#URLlink").val( '8. Error occurred while retrieving information<br />' + errorThrown + ' / ' + textStatus + ' / ' + errorThrown );
		},
		success: function( data, textStatus, XMLHttpRequest, a ) {
			$('#URLlink').val( data );
		}
	});
}

function getName( ad )
{
	$.ajax({
		url: AbsLINK + "include/Ajax.GetName.php?id=" + Id + "&player=" + Player + "&ad=" + ad,
		cache: false,
		dataType: 'html',
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$("#TV_comment").html( '9. Error occurred while retrieving information<br />' + errorThrown + ' / ' + textStatus + ' / ' + errorThrown );
		},
		success: function( data, textStatus, XMLHttpRequest, a ) {
			$("#TV_comment").html( data );
		}
	});
}

function SendTime( m )
{
	_gaq.push(['_trackEvent', 'JBWatchTime', m + '_min', Cat, Naam + '(' + Id + ')']);

	clearTimeout( Timer1 );
	if( m == 0.5 ) {
		Timer1 = setTimeout('SendTime(1)', (990 * 1 * 30) );
	}else if( m == 1 ) {
		Timer1 = setTimeout('SendTime(3)', (990 * 2 * 60) );
	}else if( m == 3 ) {
		Timer1 = setTimeout('SendTime(' + (m + 3) + ')', (990 * 2 * 60) );
	}else if( m > 3 ) {
		Timer1 = setTimeout('SendTime(' + (m + 5) + ')', (990 * 5 * 60) );
}	}

function doAjax( RequestURL, a )
{
	$.ajax({
		url: RequestURL,
		cache: false,
		dataType: 'html',
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$("#URLlink").val( '10. Error occurred while retrieving information<br />' + errorThrown + ' / ' + textStatus + ' / ' + errorThrown );
		},
		success: function( data, textStatus, XMLHttpRequest, a ) {
			if(a == 1)
			{
				$("#TV_comment").html( data );
			}else{
				$('#URLlink').val( data );
			}
		}
	});
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)  {
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			} else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{	// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};
BrowserDetect.init();
