/// <reference path="~/scripts/jquery-vsdoc.js"/>
var googleID = 'UA-2538310-4', pageTracker;

var s_hrs, s_min, l_hrs, l_min;
var sliderHtml = '', playList = new Array();
var addTimer = new Object(), removeTimer = new Object();
var streamId, streamStatus, quality, liveData;

// dummy placeholder
var requestPlayer = getQueryString('player') == 'w' ? getPlayer : getPlayerFL;
var testMode = false;

var ah, me = document.title, p = parseInt($("meta[name=p]").attr("content"), 10), IE = document.all, traceCount = 0;

jQuery.ajaxSetup({ beforeSend: function(xhr) { xhr.setRequestHeader("AJAX", "true"); } });

window.onload = delay_load;

$(document).ready(function() {
	IdealA();

	sliderHtml = $('#slider').html();
	initSliderClicks();

	setTimesToLocal();

	load();
});

function getQueryString(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null)
		return '';
	else
		return results[1];
}

function delay_load() {
	function loadLogo() {
		$('#infoBar').html('<IFRAME WIDTH="468" HEIGHT="120" SCROLLING="No" FRAMEBORDER="0" MARGINHEIGHT="0" MARGINWIDTH="0" SRC="http://img.bet-at-home.com/adiframe/3.0/976/2408308/0/113/ADTECH;target=_blank"><script language="javascript" src="http://img.bet-at-home.com/addyn/3.0/976/2408308/0/113/ADTECH;loc=700;target=_blank"></script><noscript><a href="http://img.bet-at-home.com/adlink/3.0/976/2408308/0/113/ADTECH;loc=300" target="_blank"><img src="http://img.bet-at-home.com/adserv/3.0/976/2408308/0/113/ADTECH;loc=300" border="0" width="468" height="120"></a></noscript></IFRAME>');
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		jQuery.getScript(gaJsHost + 'google-analytics.com/ga.js', function() {
			try {
				pageTracker = _gat._getTracker(googleID);
				pageTracker._trackPageview();
			} catch (ex)
				{ }
		});
	}

	$('DIV.logo').fadeIn('slow', function() {
		var jq_logo = $('#iwLogo');
		if (jq_logo.length == 1) {
			$('#iwLogo').fadeIn(800, loadLogo).hover(function() { $(this).css('opacity', .5); }, function() { $(this).css('opacity', 1); });
		} else {
			loadLogo();
		}
	});

	$('#bl_rotator').cycle({
		fx: 'fade',
		speed: 500,
		delay: 1000,
		pause: true
	});

	function _showRotator() { $('#bl_rotator').css('visibility', 'visible'); }

	window.setTimeout(_showRotator, 100);
}

function load() {
	initClocks(true);

	initCycle(false);

	checkLiveEvents();
	setInterval(checkLiveEvents, 2500000);

	switch (pid) {
		case 3:
			eventsInit();
			break;

		default:
			break;
	}
}

function eventsInit() {
	var winHeight = $(window).height()

	_heightOffset = $('div.schedule div.header').height() + $('div.schedule table.header').height();
	_showallHeight = $('div.schedule table.showall').height();
	_minimumHeight = winHeight - $('div.schedule').offset().top - $('div#footer').height() - 15;

	$('div.schedule table[class!=TV] td[class!=]').hover(
		function() { $(this).css('background-color', '#e7eff2'); },
		function() { $(this).css('background-color', ''); }
	);

	$('div.xline table[class!=TV] td[class!=]').click(function() {
		var abbr = $(this).attr('abbr');
		var strg = (abbr == '') ? $(this).text() : abbr;
		showOnly(this, strg);
	});

	$('div.day').find('label:first').show();

	$('div.schedule td[abbr=Z]').click(function() {
		$('div.day label').hide();
		$('div.day').find('label:first').show();
		$('table.showall td').css('visibility', 'hidden')

		var hidden = $('div.xline:hidden');
		var loop = hidden.length;
		hidden.slideDown(250, function() {
			loop -= 1;
			if (loop == 0) setSchedule();
		});
	});

	setSchedule();
}

function showOnly(that, strg) {
	$('div.day label').hide();
	$('div.day').find('label:first').show();
	$('table.showall td').css('visibility', 'hidden')

	var xlines = $('div.xline:contains(' + strg + ')');

	var hide = $('div.xline:not(:contains(' + strg + '))');
	var loop1 = hide.length;
	hide.slideUp(350, function() {
		loop1 -= 1;
		if (loop1 == 0) {
			hide.parent().find('div.xline:visible label:first:hidden').show();

			var css = $(that).attr('class');
			css = css.replace('E X', 'E');
			css = css.replace('F Y', 'F');
			$('div.schedule td[class=' + css + ']').css('visibility', 'visible');
			setSchedule(xlines);
		}
	});

	var loop2 = xlines.length;
	xlines.slideDown(250, function() {
		loop2 -= 1;
		if (loop2 == 0 && hide.length == 0) setSchedule(xlines);
	});
}

function showTV(id) {
	var xlines = $('div.xline:visible');
	var tvisible = $('div.tvinfo:visible');
	var tvinfo = $('div#tv_' + id);

	if (tvisible.attr('id') == tvinfo.attr('id'))
		tvinfo.slideUp(150, function() {
			setSchedule(xlines);
		});
	else
		if (tvisible.length > 0)
			tvisible.slideUp(100, function() {
				tvinfo.slideDown(250, function() {
					setSchedule(xlines);
				});
			});
	else
		tvinfo.slideDown(250, function() {
			setSchedule(xlines);
		});
}

function setSchedule(xlines) {
	xlines = SetDefault(xlines, $('div.xline'));
	showAll = $('div.xline:hidden').length > 0;

	var schedule = $('div.schedule');
	var height = schedule.height();
	var newHeight = 0;

	xlines.each(function() {
		newHeight += $(this).height();
	});

	newHeight += _heightOffset + ((showAll) ? _showallHeight : 0);
	newHeight = (newHeight < _minimumHeight) ? _minimumHeight : newHeight;
	newHeight = (newHeight < 440) ? 440 : newHeight; //workaround für hintergrundüberschneidung am seitenende

	schedule.height(newHeight);
	
	updateButtons();
}

function showVod(id, mf, format, more, typ, start) {

	var st = new Date();
	st.setFullYear(2009, 8, 5);
	
	var heute = new Date();

	if (st > heute) {
		// vor 5.9.2009
		playList[0] = { file: 'cl/presenter/intro_0' + format + '.flv', type: 'video', image: 'http://81.223.231.20/tv/img/' + id + '.jpg' }
		playList[1] = { file: 'tv/' + id + '.flv', type: 'video' }
		playList[2] = { file: 'cl/presenter/intro_0' + format + '.flv', type: 'video', image: 'http://81.223.231.20/tv/img/' + id + '.jpg' }
	}
	else {
		// nach 5.9.2009
		playList[0] = { file: 'tv/' + id + '.flv', type: 'video', image: 'http://81.223.231.20/tv/img/' + id + '.jpg' }
	}
	
	var width = (format == '1') ? '400' : '512';
	var height = (format == '1') ? '330' : '318';
	var flashVars = '&skin=/embed/dangdang.swf&bufferlength=2&streamer=rtmp://81.223.231.20/vod&volume=50&showstop=true&repeat=list&abouttext=Contents &#169; ehfTV.com&aboutlink=http://ehfTV.com&plugins=googlytics-1';
	var player = new SWFObject('/embed/player.swf', 'vod', width, height, '9', '000000');
	
	player.addParam('allowscriptaccess', 'always');
	player.addParam('allowfullscreen', 'true');
	player.addParam('flashvars', flashVars);
	player.addParam('wmode', 'opaque');

	player.write('flash');

	$('#player').attr('class', 'aspect_' + format);
	$('#overlay').show();

	return false;
}

function getPlayer() {
	var args = { p: 4500, o: streamId, q: quality };

	if (testMode)
		args['test'] = true;
	
	$.get('/wmvplayer/', args, function(html, textStatus) {
		if (textStatus == 'success') {
			$('#live').replaceWith(html);
			setLocalTime(gmtOffsetString());
		}
	});
}

function initLivePlayer(args) {
/*
	args.urlHigh, 
	args.urlLow, 
	args.urlPreroll,
	args.format
*/
	var format = args.format;

	var width = (format == '1') ? '400' : '512';
	var height = (format == '1') ? '330' : '330';
	
	var player = new SWFObject('/embed/live.player.swf', 'vod', width, height, '9', '#000000');

	player.addParam('allowscriptaccess', 'always');
	player.addParam('allowfullscreen', 'true');
	player.addParam('wmode', 'opaque');

	player.addVariable('streamhigh', args.urlHigh);
	player.addVariable('streamlow', args.urlLow);
	player.addVariable('preroll', args.urlPreroll);

	player.write('wmv');

	$('#wmv').attr('class', 'aspect_' + format);
	$('#overlay').show();
}

function getPlayerFL() {
	var args = { p: 4501, o: streamId, q: quality };
	
	if (testMode)
		args['test'] = true;

	$.post('/flplayer/', args, function(data, textStatus) {
		if (textStatus == 'success') {
			$('#live').replaceWith(data.content);
			setLocalTime(gmtOffsetString());
			if (data.loadStream == 'true') {
				initLivePlayer(data);
			}
		}
	}, 'json');
}

function checkStats() {
	var args = { p: 3000, o: streamId, s: streamStatus };
	
	if (testMode)
		args['test'] = true;
		
	$.post('/live/', args, function(data) {
		if (data.reload && streamStatus != data.status) {
			//getPlayer(streamId, quality);
			requestPlayer();
			streamStatus = data.status;
		}
		if (data.next > 0) setTimeout(checkStats, data.next);
	}, 'json');
/*
	$.getJSON('/live/', { p: 3000, o: streamId, s: streamStatus }, function(data) {
		if (data.reload && streamStatus != data.status) {
			//getPlayer(streamId, quality);
			requestPlayer();
			streamStatus = data.status;
		}
		if (data.next > 0) setTimeout('checkStats();', data.next);
	});
*/
}

function playerReady(obj) {
	var id = obj['id'];
	var player = document.getElementById(id);

	player.addControllerListener('ITEM', 'initOverlay');
	player.addControllerListener('PLAY', 'changeOverlay');

	$('#vod').each(function(){ this.sendEvent('LOAD', playList); });
}

function initOverlay(obj) {
	$('#overlay').hide();
	
	cross('player').onmouseover = function() { $('#overlay').show(); }
	cross('player').onmouseout = function() { $('#overlay').hide(); }
};

function changeOverlay(obj) {
	if (obj.state) {
		$('#overlay').hide();

		cross('player').onmouseover = function() { $('#overlay').show(); }
		cross('player').onmouseout = function() { $('#overlay').hide(); }
	}
	else {
		$('#overlay').show();

		cross('player').onmouseover = null;
		cross('player').onmouseout = null;
	}
};

function initClocks(start) {
	if (start) {
		now = new Date();

		l_hrs = now.getHours();
		l_min = now.getMinutes();

		$('#l_hrs').html(AddZero(l_hrs));
		$('#l_min').html(AddZero(l_min));

		clocks = window.setTimeout('initClocks(false);', (60 - now.getSeconds()) * 1000);

		$('#top DIV.timer').slideDown('fast');
	}
	else {
		updateClocks();

		if (window.clocks) clearTimeout(clocks);

		clocks = window.setInterval('updateClocks();', 60000);
	}
}

function updateClocks() {
	l_min++; if (l_min > 59) { l_min = 0; l_hrs++; if (l_hrs > 23) { l_hrs = 0; } }

	$('#l_hrs').html(AddZero(l_hrs));
	$('#l_min').html(AddZero(l_min));
}

function updateButtons()
{
	if(!liveData)return;
	$.each(liveData, function(i, item) {
		id = parseInt(item.id, 10);
		
		if (item.begin != -1) {

		}
		else if (item.end != -1) {
			$('#livetime_' + id).css('display', 'none');
			$('#liveplaying_' + id).css('display', 'inline');
		}
		else {
			$('#livetime_' + id).css('display', 'inline');
			$('#liveplaying_' + id).css('display', 'none');
		}
	});
}

function checkLiveEvents() {
	$.getJSON('/live/', { p: 4000 }, function(data) {
		liveData = data;
		$.each(liveData, function(i, item) {
			id = parseInt(item.id, 10);
			
			if (item.begin != -1) {
				if (window.addTimer[id]) clearTimeout(addTimer[id]);
				addTimer[id] = setTimeout('addLiveEvent(' + id + ')', item.begin);

				if (window.removeTimer[id]) clearTimeout(removeTimer[id]);
				removeTimer[id] = setTimeout('removeLiveEvent(' + id + ')', item.end);
			}
			else if (item.end != -1) {
				if (window.addTimer[id]) clearTimeout(addTimer[id]);
				addLiveEvent(id);

				if (window.removeTimer[id]) clearTimeout(removeTimer[id]);
				removeTimer[id] = setTimeout('removeLiveEvent(' + id + ')', item.end);
			}
			else {
				if (window.removeTimer[id]) clearTimeout(removeTimer[id]);
				removeLiveEvent(id);
			}
		});
	});
}

var liveSlideCount = 0;

function addLiveEvent(id) {
	if (window.addTimer[id]) clearTimeout(addTimer[id]);
	
	if ($('#slider #sld_' + id).length == 0) {
		liveSlideCount++;

		if (liveSlideCount == 1) $('#slider').html('');

		$.get('/slide/', { p: 4100, o: id }, function(html, textStatus) {
			if (textStatus == 'success') {
				var slide = document.createElement('div');

				$(slide).attr('class', 'slide');
				$(slide).attr('id', 'sld_' + id);
				$(slide).append(html);
				
				$('#slider').cycle('stop');

				var old = $('#slider').html();

				$('#slider').html('');
				$('#slider').html(old)
				$('#slider').append(slide);

				initCycle(liveSlideCount);
			}
		});

		$('#livetime_' + id).css('display', 'none');
		$('#liveplaying_' + id).css('display', 'inline');

		updateLiveButton(liveSlideCount); 
	}
}

function removeLiveEvent(id) {
	if (window.removeTimer[id]) clearTimeout(removeTimer[id]);
	
	if ($('#slider #sld_' + id).length > 0) {
		liveSlideCount--;
	
		if (liveSlideCount == 0) {
			$('#slider').cycle('stop');
			$('#slider').html(sliderHtml);

			initSliderClicks();
			initCycle(liveSlideCount); 
		}
		else {
			$('#slider').cycle('stop');
			$('#slider #sld_' + id).replaceWith('');

			var old = $('#slider').html();

			$('#slider').html('');
			$('#slider').html(old);

			if (liveSlideCount == 1) {
				var last = $('#slider [id^=sld_]');
				last.css('top', 0);
				last.css('display', 'block');
			}

			initCycle(liveSlideCount);
		}

		$('#livetime_' + id).css('display', 'inline');
		$('#liveplaying_' + id).css('display', 'none');

		updateLiveButton(); 
	}
}

function initSliderClicks() 
{
	$('#slider .slide A').click(function() {
		var source = $(this).attr('rel').split('|');
		var params = source[0];
		var vid = source[1];
		
		if(pid == 1) 
		{
			// update video
			eval('showVod(' + params +');');

			// update layer
			var path = vid.split('/');
			vid = parseInt(path[path.length - 1], 10);

			$('#overlay').html($('#overlay_' + vid).html());
		}
		else
			document.location.href = vid;

		return false;
	});
}

function initCycle(count) {
	var autostop = (count > 0) ? count * 2 : cycleLength;
	var starting = (count > 0) ? 0 : cycleStart;
	var offset = (count > 0) ? 1000 : 2000;

	$('#slider').cycle({
		fx:				'scrollVert',
		next:			'#sl_next',
		prev:			'#sl_prev',
		speed:			500,
		delay:			offset,
		timeout:		3000,
		pause:			true,
		autostop:		true,
		autostopCount:	autostop + 1,
		startingSlide:	starting
	});
}

function updateLiveButton() {
	var addon = (pid == 5) ? '_sel' : ((liveSlideCount > 0) ? '_live' : '');
	$('#livebtn').html('<img src="/img/live' + addon + '.gif" />');
}

function setTimesToLocal() {
	var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
	var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

	var localOffset = gmtOffsetString();
	var localDate = new Date();

	$('#localdate').replaceWith(days[localDate.getDay()] + ', ' + months[localDate.getMonth()] + ' ' + localDate.getDate() + ' ' + localDate.getFullYear());
	$('#localtimezone').replaceWith(localOffset);

	setLocalTime(localOffset);
}

function setLocalTime(offset) {
	$('cite').each(function() {
		var gmt = $(this).attr('gmt');

		if (gmt && gmt != '' && gmt.indexOf(':') == 2 && gmt.length >= 4) {
			var local = new Date(new Date().setUTCHours(gmt.split(':')[0], gmt.split(':')[1], 0, 0));
			$(this).html('<b>' + AddZero(local.getHours()) + ':' + AddZero(local.getMinutes()) + '</b> GMT' + offset); // + ','
			$(this).attr('gmt', '');
		}
	});
}

/* Funktionen die bereits in ehflib.js enthalten sind */
function IdealA() { $("a").focus(function() { if (this.blur) this.blur(); }); $("a[href=#]").attr("href", "").bind("click", function() { return false; }); }
function AddZero(num) { if (parseInt(num, 10) < 10) { return '0' + num; } else { return num; } }
function SetDefault(variable, value) { return (typeof variable == "undefined") ? value : ((variable === "") ? value : variable); }
function gmtOffset() { return parseInt(new Date().getTimezoneOffset(), 10) / 60; }
function gmtOffsetString() { var off = gmtOffset(); if (off < 0) return off.toString().replace('-', '+'); if (off > 0) return '-' + off.toString(); return ''; }
function jFadeIn(x, speed, opacity) { $(ToObject(x)).css("opacity", 0).show().fadeTo(speed, SetDefault(opacity, 1)); }
function jFadeOut(x, speed) { $(ToObject(x)).fadeOut(speed, function() { $(this).hide(); }); }
function ToObject(x) { return (typeof x == "object") ? x : cross(x); }
function cross(el) { return document.getElementById ? document.getElementById(el) : IE[el]; }