/*
	@filetype:	JS
	@filename:	jquery.alice-epg.js
	@authors:	j.wessel, con structores gmbh | o.ochs, acando gmbh
	@customer:	hansenet telekommunikation gmbh (alice)
	@notes:
 */

//	time and date information
var alertUri = "/vod/static/alerts.htm_fragment";
var p13nurl; // url for personalization object
var NoteUrl; // url to put ids to remember them
var RemindersUrl; // url to the remidners
var currTime; // current time, 1 or 2 digits
var timeOnEntryOfPage; // same as currTime but does not change
var currTimeFix; // fixed 2h tinespans
var currTimespan; // current timespan, dentified via currTime
var currDate; // current date
var minuten;
var stunde;
var tag;
var wochentag;
var monat;
var jahr;
var datum = new Date();

var pageDate; // date of the delivered page (can be different from the actual
// date!)
var pageTime; //date of the page Time frame (usual 2 h frame in genre view)
var pageTimestamp;

var wochentage = new Array('Montag', 'Dienstag', 'Mittwoch', 'Donnerstag',
		'Freitag', 'Samstag', 'Sonntag');
var wochentageUS = new Array('Sonntag', 'Montag', 'Dienstag', 'Mittwoch',
		'Donnerstag', 'Freitag', 'Samstag');

// customer information
var salutation; // Anrede
var salutationName; // Nachname
var salutationTimeText;
var LoggedIn;
var isLoggedInhasHomeTv; // helper variable

var LoginTitle = 'Klicken Sie hier, um sich anzumelden und Ihre persönlichen Einstellungen angezeigt zu bekommen!';
var LogoutTitle = 'Klicken Sie hier, um sich abzumelden!';

var LoginText = 'Login';
var LogoutText = 'Logout';

/* --- */

// document information
var locURL = document.URL;
var locREF = document.referrer;
var locHREF = document.location.href;
var locSRCH = window.location.search;

/* --- */

var sListT; // top offset of the station list
var sListL; // left offset of the station list

var pListT; // top offset of the program list
var pListL; // left offset of the program list

/* --- */

var btID; // id of a broadcasting
var btD_URL; // details of a broadcasting to load
var detailsX; // left position of the details layer
var detailsY; // top position of the details layer
var detailsW; // width of the details layer (already have this in the css, but
// you never know...)
var detailsH; // height of the details layer

var layerOpened; // is a layer opened
var alertOpened; // is an alert opened

/* --- */

var winW; // width of the browser window
var winH; // height of the browser window
var docWidth; // scroll width of the page
var docHeight; // scroll height of the paeg
var scrollW; // set the width for the scrollable content depending on the
// browser
var scrollH; // set the height for the scrollable content depending on the
// browser

/* --- */

var rec_on = 'Möchten Sie diese Sendung aufnehmen? Klicken Sie hier!';
var rec_off = 'Möchten Sie diese Sendung nicht mehr aufnehmen? Klicken Sie hier!';
var note_on = 'Möchten Sie diese Sendung Ihrer Merkliste hinzufügen? Klicken Sie hier!';
var note_off = 'Möchten Sie diese Sendung von Ihrer Merkliste entfernen? Klicken Sie hier!';

var isPayTitle = 'Dieser Sender ist ein PayTV-Sender!';
var isFavTitle = 'Sie haben diesen Sender in Ihrer Favoritenliste!';
var isFavisPayTitle = 'Sie haben diesen PayTV-Sender in Ihrer Favoritenliste!';

/* --- */

var filename_norm; // element normal/enabled state
var filename_act; // element active state
var filename_off; // element disabled state

var overlayCSS; // CSSObject for the overlay

/* --- */

var btCnt; // number of broadcasts inside a list, e.g. "Genreliste"
var colCnt
// number of table columns
var btCntMax = 20; // max number of broadcasts inside a list display at once
var btCntRest; // how many elements are left over after a first split (with the
// max value regarded)?
var actPage; // the "page" currently displayed
var lastPage; // last page in the generated list
var pages; // amount of pages
var page; // rows to display
var nothingHereText = 'Es sind keine Elemente zur Anzeige vorhanden!'; // if no
// element
// to be
// displayed

/* --- */

var timerOffset;
var timerOffsetTop;
var timerOffsetLeft;

/* --- */

var alertID; // id of a element that has an alert message
var alertType; // which alert to be displayed
var alertMsg; // alert message properties
var AdvancedAlertType; // which advanced alert to be displayed
var alertH; // height of the specific alert message
var alertY; // y-coordinate of the specific alert message
var alertW; // width of the specific alert message
var alertX; // x-coordinate of the specific alert message

/* --- */

var mouseX; // cursor position X
var mouseY; // cursor position Y

/* --- */

var contentDef; // what type is the content of the details layer

/* --- */

var isPersonalizationComputed = false; //flag to show if personalization method is already run

// correctly place pagination elements
function placePagination() {
	var paginationCW = $('div.listWrap').width();
	var paginationW = ($('div.listWrap').find('ul.pagination li').size() * $(
			'div.listWrap').find('ul.pagination li').width()) * 2;
	var paginationX = paginationCW / 2 - paginationW / 2 + 'px';

	$('div.listWrap').find('ul.pagination').css('left', paginationX);

	/**/

	var paginationVidCW = $('div#vidlist_pages').width();
	var paginationVidW = ($('div#vidlist_pages').find('ul.pagination li')
			.size() * $('div#vidlist_pages').find('ul.pagination li').width()) * 2;
	var paginationVidX = paginationVidCW / 2 - paginationVidW / 2 + 'px';

	$('div#vidlist_pages').find('ul.pagination').css('left', paginationVidX);
}

// hande banner placement
function showBanner(elem) {
	elem.find(".btTsr").each( function() {
		// console.log($(this));
			$(this).show();
		});
}
function placeBanner() {
	var elemsize;
	var element;
	$(".period").each( function(i, overelem) {
		$(overelem).find("tbody tr:first").each( function(j, elem) {
			elemsize = 999;
			element = null;
			$(elem).find("td:lt(5)").each( function(k, subelem) {
				if ($(subelem).find(".btList li").size() < elemsize) {
					elemsize = $(subelem).find(".btList li").size();
					element = $(subelem);
				}
			});
			// console.log("Period " + i + " - Row " + j + " Size " + elemsize);
			if (element) {
					$(element).append(bannerTemplate);
					showBanner($(element));
				}
			})
	})
}

// function for LogIn
function LogMeIn() {
//	$(this).find('span').text(LogoutText).attr('title', LogoutTitle).unbind(
//			'click').bind('click', LogMeOut);
	console.log("Redirecting to " +  LoginUrl + "?" + "service=" + encodeURIComponent(window.location.href));
	window.location.href = LoginUrl + "?" + "service="
			+ encodeURIComponent(window.location.href);
	return false;
}
// function for LogOut
function LogMeOut() {
//	$(this).find('span').text(LoginText).attr('title', LoginTitle).unbind(
//			'click').bind('click', LogMeIn);
	console.log("Redirecting to " +  LogoutUrl + "?" + "service=" + encodeURIComponent(window.location.href));
	window.location.href = LogoutUrl + "?" + "service="
			+ encodeURIComponent(window.location.href);
	return false;
}

/**
 * FIXME: Does not work
 * Redirect to Logout with Login-Page as target. Used
 * to Logout and then Login the user
 */
function ReLogin() {
	window.location.href = LogoutUrl + "&" + "service=" 
		+ encodeURIComponent(LoginUrl + "?" + "service=" + encodeURIComponent(window.location.href));
}

function turn_single_note_on(noteid) {
	$(
			'#btEL_' + noteid)
			.find('.tgl_note')
			.addClass('act').attr(
					'title',
					note_off);
	$(
			'#btEL_' + noteid)
			.find('#tgl_note')
			.addClass('act').attr(
					'title',
					note_off);

	// Details layer
	$(
			'#btD_' + noteid)
			.find('#tgl_note')
			.find('a').addClass(
					'act').attr(
					'title',
					note_off);
}

/* --- */
function turn_note_on(noteid) {
	$(
			'#btEL_' + userpreferences.epg.noteIds[noteid])
			.find('.tgl_note')
			.addClass('act').attr(
					'title',
					note_off);
	$(
			'#btEL_' + userpreferences.epg.noteIds[noteid])
			.find('#tgl_note')
			.addClass('act').attr(
					'title',
					note_off);

	// Details layer
	$(
			'#btD_' + userpreferences.epg.noteIds[noteid])
			.find('#tgl_note')
			.find('a').addClass(
					'act').attr(
					'title',
					note_off);
}

function turn_note_off(noteid) {
	$(
			'#btEL_' + userpreferences.epg.noteIds[noteid])
			.find('.tgl_note')
			.removeClass('act').attr(
					'title',
					note_on);
	$(
			'#btEL_' + userpreferences.epg.noteIds[noteid])
			.find('#tgl_note')
			.removeClass('act').attr(
					'title',
					note_on);

	// Details layer
	$(
			'#btD_' + userpreferences.epg.noteIds[noteid])
			.find('#tgl_note')
			.find('a').removeClass(
					'act').attr(
					'title',
					note_on);
}

function turn_single_note_off(noteid) {
	$(
			'#btEL_' + noteid)
			.find('.tgl_note')
			.removeClass('act').attr(
					'title',
					note_on);
	$(
			'#btEL_' + noteid)
			.find('#tgl_note')
			.removeClass('act').attr(
					'title',
					note_on);

	// Details layer
	$(
			'#btD_' + noteid)
			.find('#tgl_note')
			.find('a').removeClass(
					'act').attr(
					'title',
					note_on);
}

// personalize the GUI using JSON-data
function personalize() {
	noCache = new Date().getTime();
	$
			.getJSON(p13nurl,  { "noCache": noCache }, function(json) {
					userpreferences = json;	
					if (!json.isSuccessful && json.errorMessageDiv) {
						displayJsonMessage(json.errorMessageDiv);
					} else 	if (userpreferences.isSuccessful) {

						// logged in master account without iptv
						if ((userpreferences.isLoggedIn)
								&& (userpreferences.user.isMasterUser)
								&& (!userpreferences.user.hasHomeTv)) {
							isLoggedInhasHomeTv = 'master';
						}

						// logged in, sub account
						if ((userpreferences.isLoggedIn)
								&& (!userpreferences.user.isMasterUser)) {
//							console.log('user logged in, sub account');
							isLoggedInhasHomeTv = 'sub';
						}

						// logged in, master, hometv
						if ((userpreferences.isLoggedIn)
								&& (userpreferences.user.isMasterUser)
								&& (userpreferences.user.hasHomeTv)) {
//							console.log('user logged in, masteraccount, hometv');
							isLoggedInhasHomeTv = 'true';
						}
						
						// not logged in or login stats unknown
						if ((!userpreferences.isLoggedIn)
								|| (!userpreferences.isLoggedIn)
								|| (typeof (userpreferences.isLoggedIn) == 'undefined')) {
//							console
//									.log('user not logged in, account type unknown, hometv unknown');
							isLoggedInhasHomeTv = 'false';
						}

						if (userpreferences.isLoggedIn) {
//							console.log(userpreferences.user.lastName);
//							console.log("User is logged in");

							// Login-/ Logout-button 
							$('a#login').find('span').text(LogoutText).attr('title', LogoutTitle);
							$('a#login').unbind('click');
							$('a#login').bind('click', LogMeOut);

							$('a#login').css('visibility', 'visible');
							
							// Favorites-button
							$('a#favorites').css('visibility', 'visible');

							// console.log("Displaying record buttons: " +
							// userpreferences.epg.recIds);
							if (userpreferences.epg.recIds)
								$(userpreferences.epg.recIds)
										.each(
												function(recid) {
													$(
															'#btEL_' + userpreferences.epg.recIds[recid])
															.find('.tgl_rec')
															.addClass('act')
															.attr('title',
																	rec_off);
													$(
															'#btEL_' + userpreferences.epg.recIds[recid])
															.find('#tgl_rec')
															.addClass('act')
															.attr('title',
																	rec_off);

													// Details layer
													$(
															'#btD_' + userpreferences.epg.recIds[recid])
															.find('#tgl_rec')
															.find('a')
															.addClass('act')
															.attr('title',
																	rec_off);
												});

							// console.log("Displaying note buttons: " +
							// userpreferences.epg.noteIds);
							$(userpreferences.epg.noteIds)
									.each(function call(noteid){turn_note_on(noteid)});

							// console.log("Displaying favorites: " +
							// userpreferences.epg.favChannels);
							if (isLoggedInhasHomeTv == 'true') $(userpreferences.epg.favChannels)
									.each( function(channelId) {
										// console.log(userpreferences.epg.favChannels[channelId]);
											if (userpreferences.epg.favChannels)
												$(
														'ul.st#' + userpreferences.epg.favChannels[channelId])
														.not('ul.st.isPay')
														.addClass('isFav')
														.attr('title',
																isFavTitle);
											$(
													'ul.st.isPay#' + userpreferences.epg.favChannels[channelId])
													.removeClass('isPay')
													.addClass('isFavisPay')
													.attr('title',
															isFavisPayTitle);

											$('ul.st.isPay').attr('title',
													isPayTitle);
										});
						} else {
							$('a#login').css('visibility', 'visible');
						}
					}

					else {
						// console.log("not Successful");
						// console.log(userpreferences.errorMessageDiv);
						displayJsonMessage(userpreferences.errorMessageDiv);
					}
//					console.log('Personalized: ');
//					console.log('layerOpened: ' + layerOpened);
//					console.log('alertOpened: ' + alertOpened);
//					console.log('isLoggedInhasHomeTv: ' + isLoggedInhasHomeTv);
				});
	isPersonalizationComputed = true;
}

/**
 * Displays a message in the epg_m block. Then slowly fades in this block.
 * @param message usually a message from a json requests
 * @return -
 */
function displayJsonMessage(message) {
	$('#epg_m').fadeOut("slow");
	$('#epg_m').html(message);
	$('#epg_m').fadeIn("slow");
}

// add rollovers to elements with the class 'hasRO'
function hasRO_on() {
	if (!($(this).hasClass('act'))) {
		filename_norm = $(this).attr('src');
		filename_act = filename_norm.replace(/norm/, "act");
		// filename_off = filename_norm.replace(/norm/, "off");
		$(this).attr('src', filename_act);
	}
}
//remove rollovers from elements with the class 'hasRO'
function hasRO_off() {
    if (!($(this).hasClass('act'))) {
        filename_act = $(this).attr('src');
        // filename_off = filename_act.replace(/act/, "off");
        filename_norm = filename_act.replace(/act/, "norm");
        $(this).attr('src', filename_norm);
    }
} 

function showReminders() {
	if (isPersonalizationComputed) {
		if (isLoggedInhasHomeTv) {
			if (isLoggedInhasHomeTv == 'true') { // it is really a string
				window.location.href = RemindersUrl;
			} else {
				showAdvancedAlert();
				return false;
			}
		} else {
			return false;
		}
	} else {
		return false;
	}
	
}

// control current page
function checkCurrPage() {
	if (actPage == 1) {
		$('div.listWrap').find('ul.pagination').find('li.fwd').addClass('act');
		$('div.listWrap').find('ul.pagination').find('li.last').addClass('act');

		$('div.listWrap').find('ul.pagination').find('li.bwds').removeClass('act');		
		$('div.listWrap').find('ul.pagination').find('li.first').removeClass('act');
	}

	if ((actPage > 1) && (actPage < lastPage)) {
		$('div.listWrap').find('ul.pagination').find('li.fwd').addClass('act');
		$('div.listWrap').find('ul.pagination').find('li.last').addClass('act');

		$('div.listWrap').find('ul.pagination').find('li.bwds').addClass('act');
		$('div.listWrap').find('ul.pagination').find('li.first').addClass('act');
	}

	if (actPage == lastPage) {
		$('div.listWrap').find('ul.pagination').find('li.fwd').removeClass('act');
		$('div.listWrap').find('ul.pagination').find('li.last').removeClass('act');

		$('div.listWrap').find('ul.pagination').find('li.bwds').addClass('act');
		$('div.listWrap').find('ul.pagination').find('li.first').addClass('act');
	}
	$('div.listWrap').find('ul.pagination').find('li').not('li.page').find('a.act').removeClass('act');
	$('div.listWrap').find('ul.pagination').find('li.act').not('li.page').find('a').addClass('act');
}
// hide table rows
function tableHideInit() {
	$('div.listWrap').find('table.listTable').find('tbody tr').hide();
}
// gotoPage function triggered by pagination elements
function gotoPage() {
	var $elArray = $(this).parents('div.listWrap').find('table.listTable')
			.find('tbody tr');
	actPage = parseInt(($('div.listWrap').find('ul.pagination:first').find(
			'li.page').find('a.act').text()));

	// pages
	if ($(this).parent('li').hasClass('page')) {
		tableHideInit();

		actPage = parseInt($(this).text());
		page = actPage - 1;

		$('ul.pagination').find('li.page a.act').removeClass('act');
		$('ul.pagination').find('li:eq(' + (actPage + 1) + ')').find('a').addClass('act');


		$elArray.slice(page * btCntMax, page * btCntMax + btCntMax).show();
	}
	// first, last
	if ($(this).parent('li').hasClass('first')) {
		if (actPage == 1) {
		} else {
			tableHideInit();

			$('ul.pagination').find('li.page a.act').removeClass('act');
			$('ul.pagination').find('li.page:eq(0)').find('a').addClass('act');
			actPage = 1;
			page = 0;

			$elArray.slice(page * btCntMax, page * btCntMax + btCntMax).show();
		}
	}
	if ($(this).parent('li').hasClass('last')) {
		if (actPage == lastPage) {
		} else {
			tableHideInit();

			$('ul.pagination').find('li.page a.act').removeClass('act');
			$('ul.pagination').find('li.page:last').find('a').addClass('act');
		
			actPage = lastPage;
			page = actPage - 1;

			$elArray.slice(page * btCntMax).show();
		}
	}

	// previous, next
	if ($(this).parent('li').hasClass('bwds')) {
		if (actPage == 1) {
		} else {
			tableHideInit();

			$('ul.pagination').find('li.page a.act').removeClass('act');
			$('ul.pagination').find('li.page:eq(' + (actPage - 2) + ')').find(
					'a').addClass('act');
			actPage--;

			page = actPage - 1;
			$elArray.slice(page * btCntMax, page * btCntMax + btCntMax).show();
		}
	}
	if ($(this).parent('li').hasClass('fwd')) {
		if (actPage > (lastPage - 1)) {
		} else {
			tableHideInit();

			$('ul.pagination').find('li.page a.act').removeClass('act');
			$('ul.pagination').find('li.page:eq(' + (actPage) + ')').find('a')
					.addClass('act');
			actPage++;

			page = actPage - 1;
			$elArray.slice(page * btCntMax, page * btCntMax + btCntMax).show();
		}
	}
	placePagination();
	checkCurrPage();
	return false;
}
// get amount of available elements inside a list table and handle those
function getBtCnt() {
	$('table.listTable')
			.each(
					function() {
						colCnt = $(this).find('colgroup').find('col').size();

						var nothingHere = '<tr><td colspan="' + colCnt
								+ '" id="nothingHere">' + nothingHereText
								+ '<\/td><\/tr>';

						// addSpacer rows
						$('table.listTable')
								.find('thead tr:last')
								.after(
										'<tr class="spacer"><th colspan="' + colCnt + '">&nbsp;<\/th><\/tr>');
						$('table.listTable')
								.find('tfoot tr:first')
								.before(
										'<tr class="spacer"><th colspan="' + colCnt + '">&nbsp;<\/th><\/tr>');

						btCnt = $(this).find('tbody tr').size();
						// console.log('Anzahl der Sendungen: '+btCnt+' Maximal
						// angezeigt: '+btCntMax);

						btCntRest = btCnt - btCntMax;
						// console.log('Anzahl der Sendungen: '+btCnt+' Maximal
						// angezeigt: '+btCntMax);
						tableHideInit();

						// create a clone of the pagination list and append
						// it after the bottom of the table
						$(this).parent('div.listWrap')
								.find('ul.pagination').clone().addClass(
										'bot').appendTo(
										$(this).parent('div.listWrap'));

						// show and activate pagination only if there are more
						// elements than the specified max visible value
						if (btCnt > btCntMax) {
							$('div.listWrap').find('ul.pagination').find(
									'li.fwd').addClass('act');
							$('div.listWrap').find('ul.pagination').find(
									'li.last').addClass('act');

							// show first table rows
							$(this).find('tbody tr').slice(0, btCntMax).show();

							// generate first page link
							$(this)
									.parent('div.listWrap')
									.find('ul.pagination')
									.show()
									.find('li.bwds')
									.after(
											'<li class="page"><a href="#" class="act" title="Gehe zu Seite: 1">1</a></li>');

							// generate page links
							for ( var count = 0; btCntRest > 0; count++) {
								btCntRest = btCntRest - btCntMax;
								// console.log('Verbleibend: '+btCntRest);
								$(this).parent('div.listWrap').find(
										'ul.pagination').show().find(
										'li.page:last').after(
										'<li class="page"><a href="#" title="Gehe zu Seite: '
												+ parseInt(count + 2) + '">'
												+ parseInt(count + 2)
												+ '</a></li>');
							}


							// get the last page, get amount of pages
							lastPage = parseInt($(this).parent('div.listWrap')
									.find('ul.pagination.bot').find(
											'li.page:last').text());
							pages = lastPage;

							// debugger
							// debugPage();
						} else if (btCnt < btCntMax) {
							$(this).find('tbody tr').show();
						} else if (btCnt == btCntMax) {
							$(this).find('tbody tr').show();
						}
						if (btCnt == 0) {
							// display "nothing here"-content
							$(this).find('tbody').append(nothingHere);
							$(this).find('tbody tr').show();
						} else {
							// nothing to do here
						}

						// bind a gotoPage function to every link inside the
						// pagination
						$('ul.jspagination').each( function() {
							$(this).find('li a').bind('click', gotoPage);
							$(this).find('li a').bind('click', checkCurrPage);
						});
						
						checkCurrPage();
					});
}

function setstListOlProps() {
	var liCnt = $('div#stList ol li').size();
	$('div#stList ol').css('width', (liCnt * 176) + 'px');
}

function setZebra() {
	$('table.period tbody').find('tr:even').addClass('even');
	$('table.period tbody').find('tr:odd').addClass('odd');

	$('table.listTable tbody').find('tr:even').addClass('even');
	$('table.listTable tbody').find('tr:odd').addClass('odd');
}

// function to set the width of the scrollable area
function setScrollOnEvent() {
    $(window).unbind("resize");
    setScroll();
	$(window).bind("resize", setScrollOnEvent);
}

function setScroll() {


	winW = $(window).width();
	winH = $(window).height();
//	scrollWOld = scrollW;
//	scrollHOld = scrollH;
	
//	scrollW = ($('body').width() - 100 + 'px'); // needs finetuning
//	scrollWSt = ($('body').width() - 116 + 'px'); // needs finetuning

	scrollW = (winW - 100 + 'px'); // needs finetuning
	scrollWSt = (winW - 100 + 'px'); // needs finetuning
	
	scrollH = (winH - 240 + 'px'); // needs finetuning

	// console.log(scrollW + " : " + scrollH);
	scrollConCSS = {
			//'overflow':'auto',
			//'float':'left',
			'width':scrollW,
			'height':scrollH

	};
	
	$('div#scrollCon').css(scrollConCSS);
	$('div#stList').css('width', scrollWSt); // minus scrollbar

}

// set left offset of the station list
function setstListO() {
	$('div#stList ol').css('left', -pListL);
}

// get offsets of the program list
function getpListO() {
	pListT = $('div#pList').scrollTop();
	pListL = $('div#scrollCon').scrollLeft();

	setstListO();
}

// mouseOver/mouseOut on table headers
function activatePeriod() {
	$(this).parents('tr').addClass('act');
}
function deactivatePeriod() {
	$(this).parents('tr').not('tr.on').removeClass('act');
}

// trigger the display of the periods
function togglePeriod() {
	// user clicks on table header which is currently in 'opened state' - 'on'
	if ($(this).parents('tr').hasClass('on')) {
		$('table.period').children('thead').find('tr').removeClass('on');
		$('table.period').children('tbody').hide();

		$(this).parent('tr').removeClass('on');

		$(this).parents('table.period').children('tbody').hide();
		$(this).parents('table.period').next('table.period').children('tbody')
				.show();
		$(this).parents('table.period').next('table.period').children('thead')
				.find('tr').addClass('act').addClass('on');
	}

	// user clicks on table header which is currently in 'closed state'
	else {
		$('table.period').children('thead').find('tr').removeClass();
		$('table.period').children('tbody').hide();

		$(this).parent('tr').addClass('act').addClass('on');

		$(this).parents('table.period').children('tbody').show();
	}

	// placeBanner();
	return false;
}

function togglePeriodNight() {
	if ($(this).parents('tr').hasClass('on')) {
	} else {
		$('table.period').children('thead').find('tr').removeClass();
		$('table.period').children('tbody').hide();

		$(this).parent('tr').addClass('act').addClass('on');
		$(this).parents('table.period').children('tbody').show();
	}
	// placeBanner();
	return false;
}

// toggle the record-buttons on/off
function toggle_rec() {
	btID = $(this).parents('div').attr('id')
			|| $(this).parents('tr').attr('id'); // e.g. btEL_12343

	if (isLoggedInhasHomeTv == 'true') {
		if ($(this).hasClass('act')) {
			$(this).removeClass('act');

			$(this).attr('title', rec_on);

			// TODO: Oliver, backend aufrufen
			alert("TODO: Noch nicht implementiert, Aufruf des Backends mit der Sendungs-ID: "
					+ btID
					+ " und der URL "
					+ btD_URL
					+ ", Element wurde von der Aufnahme ausgenommen!");
		} else {
			$(this).addClass('act');

			$(this).attr('title', rec_off);

			// TODO: Oliver, backend aufrufen
			alert("TODO: Noch nicht implementiert, Aufruf des Backends mit der Sendungs-ID: "
					+ btID
					+ " und der URL "
					+ btD_URL
					+ ", Element zur Aufnahme markiert!");
		}
	}

	if ((isLoggedInhasHomeTv == 'sub') && (alertOpened != true) ){
		// alert('Bitte anders einloggen!');
		showAdvancedAlert();
	}

	if ((isLoggedInhasHomeTv == 'master') && (alertOpened != true) ){
		// alert('Bitte anders einloggen!');
		showAdvancedAlert();
	}

	if ((isLoggedInhasHomeTv == 'false') && (alertOpened != true) ){
		// alert('Bitte einloggen!');
		showAdvancedAlert();
	}
}
// toggle the note-buttons on/off
function toggle_note() {
	btID =  $(this).parents('.vevent').attr('id')	
			|| $(this).parents('div').attr('id')
			|| $(this).parents('tr').attr('id')
			|| $(this).parents('ul').attr('id')
			|| $(this).parents('li').attr('id'); // e.g. btEL_12343
	btID = btID.replace(/btEL_/g, "");
	btID = btID.replace(/btEl_/g, "");
	btID = btID.replace(/btD_/g, "");
	// console.log("toggle_note remembering : " + btID);
	
	if (isLoggedInhasHomeTv == 'true') {
		if ($(this).hasClass('act')) {
			turn_single_note_off(btID);
			$.getJSON(NoteUrl, {
				"id" :btID,
				"action" :"remove"
			}, function(json) {
				if (!json.isSuccessful && json.errorMessageDiv) {
					displayJsonMessage(json.errorMessageDiv);
				}
			});
			
			
		} else {
			turn_single_note_on(btID);
			$.getJSON(NoteUrl, {
				"id" :btID,
				"action" :"add"
			}, function(json) {
				if (!json.isSuccessful && json.errorMessageDiv) {
					displayJsonMessage(json.errorMessageDiv);
				}
			});
		}
	}

	if ((isLoggedInhasHomeTv == 'sub') && (alertOpened != true) ){
		// alert('Bitte anders einloggen!');
		showAdvancedAlert();
	}

	if ((isLoggedInhasHomeTv == 'master') && (alertOpened != true) ){
		// alert('Bitte anders einloggen!');
		showAdvancedAlert();
	}

	if ((isLoggedInhasHomeTv == 'false') && (alertOpened != true) ){
		// alert('Bitte einloggen!');
		showAdvancedAlert();
	}
	
	return false;
}

// set icon properties
function setIconProps() {
	$('li.btIcons a.tgl_rec').attr('title', rec_on);
	$('li.btIcons a.tgl_note').attr('title', note_on);
}

// toggle between trailer-video and trailer-information
function toggleTrailer() {
	$(this).parents('div#btD_l').find('div#btD_vTrailer')
			.find('div#btD_vTitle').hide();
	$(this).parents('div#btD_l').find('div#btD_vTrailer').find(
			'div#btD_vlonginfo').hide();
	$(this).parents('div#btD_l').find('div#btD_vTrailer').find('a.noFlash')
			.show();

	$(this).parents('ul').find('li#viewInfos').show()
			.bind('click', toggleInfos);
	$(this).parents('ul').find('li#viewTrailer')
			.hide();
	loadVoDPlayer();
}

function toggleInfos() {
	$(this).parents('div#btD_l').find('div#btD_vTrailer')
			.find('div#btD_vTitle').show();
	$(this).parents('div#btD_l').find('div#btD_vTrailer').find(
			'div#btD_vlonginfo').show();
	$(this).parents('div#btD_l').find('div#btD_vTrailer').find('a.noFlash')
			.hide();

	$(this).parents('ul').find('li#viewTrailer').show().bind('click',
			toggleTrailer);
	$(this).parents('ul').find('li#viewInfos').hide();
	unloadVoDPlayer();

}

// toggle display of details layer
function showDetails() {
	// console.log("Hallo");
	btID = $(this).parents('div').attr('id') || $(this).attr('id')
			|| $(this).parents('li').attr('id')
			|| $(this).parents('tr').attr('id'); // e.g. btEL_12343

//	console.log("btID");
//	console.log(btID);

	btD_URL = $(this).attr('href');
//	console.log("btD_URL");
//	console.log(btD_URL);
	
	if (!btD_URL) {
		btD_URL = $(this).parent().attr('href')
//		console.log("Found parent");
//		console.log("btD_URL");
//		console.log(btD_URL);
	}
	
	if (btD_URL) {
		detailsW = $('div#details').width();
	
		
		winW = $(window).width();
		winH = $(window).height();
	
		docWidth = $(document).width();
		docHeight = $(document).height();
	
			
		overlayCSS = {
			width :winW,
			height :docHeight,
			display:'block'
		}
		
		$('div#overlay').css(overlayCSS);
		
	
		$('div#details')
				.find('#detailsLoader')
				.load(
						btD_URL + " .vevent",
						function() {
							$('div#overlay')
									.show(
											function() {
												detailsH = $('div#details')
														.height();
												detailsY = (winH / 2)
														- (detailsH / 2);
												
												/*
												if (detailsY < 5) {
													detailsY = 5;
												}
												*/
												if(docWidth < winW) {
													detailsX = (docWidth / 2) - (detailsW / 2);
												}
												else {
													detailsX = (winW / 2) - (detailsW / 2);
												}
												
												var detailsTop = $(window).scrollTop();
												
												detailsCSS = {
													left:detailsX,
													top:Math.floor(detailsY+detailsTop+(detailsH / 10))
												}
	
												contentDef = $('div#btD').find(
														'p#contentDef').text();
												
	//											console.log("ContentDef:" + contentDef); console.log(contentDef);
												$(
														'div#details div#details_t div#details_t_m')
														.find('h1').remove();
	
												if (contentDef == 'EPG') {
													$(
															'div#details div#details_t div#details_t_m a#closeLayer')
															.before(
																	'<h1><img src="/vod/img/programminfo.png" alt="Programminfo" id="h1_programminfo" /></h1>');
												} else if (contentDef == 'VoD') {
													$(
															'div#details div#details_t div#details_t_m a#closeLayer')
															.before(
																	'<h1><img src="/vod/img/filmdetails.png" alt="Filmdetails" id="h1_filmdetails" /></h1>')
												} else { // default if nothing
													// present
													$(
															'div#details div#details_t div#details_t_m a#closeLayer')
															.before(
																	'<h1>Detailinformationen</h1>');
												}
	
												$('div#details').css(detailsCSS)
														.fadeIn('slow');
	
												layerOpened = true;
	//											console.log(layerOpened);
												
												if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
													//	transparency fixes
													$('div#details img#details_t_l').ifixpng();
													$('div#details img#details_t_r').ifixpng();
													$('div#details img#details_b_l').ifixpng();
													$('div#details img#details_b_r').ifixpng();
													
													$('div#details div#details_t_m a#closeLayer').find('img').ifixpng();
													$('div#details div#details_t_m h1 img').ifixpng();
													$('div#btD div#btD_l div#btD_st_shortdate ul li#station img').ifixpng();
													
													/* needs a fix if enabled	*/
													/*
													$('div#details').find(
														'#detailsLoader')
														.find('a')
														.ifixpng();
													*/
												}
												
												personalize();
												
												$('div#details div#details_t div#details_t_m a#closeLayer').bind('click', hideDetails);
												$('div#details').find(
														'#detailsLoader').find(
														'.hasRO').bind('mouseover',
														hasRO_on);
												$('div#details').find(
														'#detailsLoader').find(
														'.hasRO').bind('mouseout',
														hasRO_off);
	
												$('div#details')
														.find('#detailsLoader')
														.find(
																'div#tgl_vOpt ul li#viewTrailer a')
														.bind('click',
																toggleTrailer);
												$('div#details')
														.find('#detailsLoader')
														.find(
																'div#tgl_vOpt ul li#viewInfos a')
														.bind('click', toggleInfos);
	
												$('div#details')
														.find('#detailsLoader')
														.find(
																'div#tgl_vOpt ul li#tgl_rec a')
														.bind('click', toggle_rec);
												$('div#details')
														.find('#detailsLoader')
														.find(
																'div#tgl_vOpt ul li#tgl_note a')
														.bind('click', toggle_note);
	
												$('div#details')
														.find('#detailsLoader')
														.find(
																'div#tgl_opt ul li#tgl_rec a')
														.bind('click', toggle_rec);
												$('div#details')
														.find('#detailsLoader')
														.find(
																'div#tgl_opt ul li#tgl_note a')
														.bind('click', toggle_note);
												
												$('div#details')
														.find('.more')
														.each( function() {
															$(this).bind('click', showDetails);
														});
										  	
											}).bgiframe();
						});
		}
	return false;
}

// toggle hide of details layer
function hideDetails() {
	$('div#details').hide();
	$('div#details').find('#detailsLoader'); // this will be added later to
	// remove all the contents:
	// .empty().append('&nbsp;');
	personalize();
	$('div#overlay').hide();

	layerOpened = false;
	return false;
}

// reposition and reformat layers if necessary
function posLayers() {
	if (layerOpened == true) {
		winW = $(window).width();
		winH = $(window).height();

		docWidth = $(document).width();
		docHeight = $(document).height();

		detailsH = $('div#details').height();
		detailsW = $('div#details').width();

		detailsY = (winH / 2) - (detailsH / 2);
		if (detailsY < 5) {
			detailsY = 5;
		}
		detailsX = (winW / 2) - (detailsW / 2);

		showOverlay();
		
		detailsCSS = {
			left :detailsX,
			top :detailsY
		}

		$('div#details').css(detailsCSS).scrollTop(detailsY);
	}
}

// set the timespan (eg in the dropdown)
function setTime() {
	currTime = $('#gotoTimespan option:selected').val();
	// console.log("setTime: " + currTime);
	getTime();
}

function setTimeToValue() {
	now = new Date();
	currTime = now.getHours();
	getTime();
}
// get the current time for usage in dropdowns and program list
function getTime() {
	if ((currTime > 5) && (currTime < 12)) {
		currTimespan = 'Vormittag';
	}
	if ((currTime >= 12) && (currTime < 18)) {
		currTimespan = 'Nachmittag';
	}
	if ((currTime >= 18)) {
		currTimespan = 'Abend';
	}
	if ((currTime >= 0) && (currTime <= 5)) {
		currTimespan = 'Nacht';
	}

	switch (currTimespan) {
	/* Vormittag 06 - 12 */
	case 'Vormittag':
		$('table.period').removeClass('curr').find('thead tr').removeClass(
				'act').removeClass('on');
		$('table.period#p0').addClass('curr').find('thead tr').addClass('act')
				.addClass('on');

		$('table.period').find('tbody').hide();
		$('table.period#p0').find('tbody').show();
		break;

	/* Nachmittag 12 - 18 */
	case 'Nachmittag':
		$('table.period').removeClass('curr').find('thead tr').removeClass(
				'act').removeClass('on');
		$('table.period#p1').addClass('curr').find('thead tr').addClass('act')
				.addClass('on');

		$('table.period').find('tbody').hide();
		$('table.period#p1').find('tbody').show();
		break;

	/* Abend 18 - 24 */
	case 'Abend':
		$('table.period').removeClass('curr').find('thead tr').removeClass(
				'act').removeClass('on');
		$('table.period#p2').addClass('curr').find('thead tr').addClass('act')
				.addClass('on');

		$('table.period').find('tbody').hide();
		$('table.period#p2').find('tbody').show();
		break;

	/* Nacht 0 - 6 */
	case 'Nacht':
		$('table.period').removeClass('curr').find('thead tr').removeClass(
				'act').removeClass('on');
		$('table.period#p3').addClass('curr').find('thead tr').addClass('act')
				.addClass('on');

		$('table.period').find('tbody').hide();
		$('table.period#p3').find('tbody').show();
		break;
	}

	if ((currTime % 2) == 0) {
		currTimeFix = currTime;
	} else {
		currTimeFix = (currTime - 1);
	}
	
	now = new Date();
	hour = now.getHours(); 
	// console.log(hour + " : " + currTime);
	if ($('#pageDate').text() == $('#today').text()) {
		// console.log("timeOnEntryOfPage: " + timeOnEntryOfPage + " - currTime: " + currTime);
		if (hour == currTime || hour -1 == currTime) {
			// console.log("equals -> unbind");
			$('#showCurrent').addClass('act');
			$('#showCurrent').unbind('click');
		} else {
			// console.log("!equals -> bind click get Time");
			$('#showCurrent').removeClass('act');
			$('#showCurrent').bind('click', setTimeToValue); //  
		}
	}

	$('#gotoTimespan').find('option:selected').each(function(){ $(this).removeAttr("selected") });
	$('#gotoTimespan').find('option[value='+currTimeFix+']').attr("selected", "selected");
	$('#datehourelem').val(currTimeFix);
	
	if (pageTime && pageTime != currTimeFix) {
		// page is a genre page, so switch page imediatly
		$('#genlist').submit();
	}
	// console.log('currTime: '+currTime);
	// console.log('currTimeFix: '+currTimeFix);

	// placeBanner();
}

// get the current date for global usage
function getDate() {
	minuten = datum.getMinutes();
	stunde = datum.getHours();
	tag = datum.getDate().toString();
	wochentag = datum.getDay();
	monat = (datum.getMonth() + 1).toString();
	jahr = datum.getFullYear();

	currTime = stunde;
	if (!timeOnEntryOfPage) {
		// first time this method is entered
		timeOnEntryOfPage = currTime;
		if (pageTime) {
			currTime = pageTime;
			
		}
	}
	
	if (tag.length == 1) {
		tag = '0' + tag;
	}
	if (monat.length == 1) {
		monat = '0' + monat;
	}
	/* set up and edit variables: END */

	/* check for timespans like morning, evening, etc.: START */
	if (stunde < 12) {
		salutationTimeText = 'Guten Morgen, ';
	}

	else if ((stunde >= 12) && (stunde < 18)) {
		salutationTimeText = 'Guten Tag, ';
	}

	else if ((stunde >= 18) && (stunde < 22)) {
		salutationTimeText = 'Guten Abend, ';
	} else { // night time (could be from 0 o'clock to 6 o'clock)
		salutationTimeText = 'Gute Nacht, ';
	}
	/* check for timespans like morning, evening, etc.: START */

	/* handle customer's login-status: START */
	if ((typeof (LoggedIn) != 'undefined') && (LoggedIn == true)) {
		salutation = 'Herr';
		salutationName = 'Mustermann';
	} else if ((typeof (LoggedIn) != 'undefined') && (LoggedIn == false)) {
		salutation = 'lieber';
		salutationName = 'Alice Kunde';
	} else {
		salutation = 'lieber';
		salutationName = 'Alice Kunde';
	}
	/* handle customer's login-status: END */

	// console.log(salutationTimeText+' '+salutation+' '+salutationName+', es
	// ist '+wochentage[wochentag-1]+', der '+tag+'.'+monat+'.'+jahr);
	// console.log('currTime is: '+currTime);
	getTime();
	getPageDate();
	refreshDate();
	$('li#tab_epg a.act,li#tab_vod a.act,li#tab_notelist a.act').before(
			'<span id="currDate">' + pageDate + '<\/span>');// '+wochentage[wochentag-1]+',
	// '+tag+'.'+monat+'.'+jahr+'
	// console.log("PageDate is " + pageDate);
}

// get the page's date and toggle events if currDate and pageDate mismatch
function getPageDate() {
	pageDate = $('body p#pageDate').text(); // 17.10.2008
	pageDates = pageDate.split(".");
	pageDateAsDate = new Date(pageDates[2], pageDates[1] - 1, pageDates[0]);
	// console.log("PageDate as Date: " + pageDateAsDate);
	pageDate = wochentageUS[pageDateAsDate.getDay()] + ", " + pageDate;
	
	
}

// get the page's date and toggle events if currDate and pageDate mismatch
function refreshDate() {
	pageTimestamp = $('body p#today').text(); // 17.10.2008
	currDate = tag + '.' + monat + '.' + jahr;

	var pageDateParsed = pageTimestamp.replace(/\./g, "");
	var today = tag + monat + jahr;

	// console.log('This current date is: '+currDate);
	// console.log('This page has the timestamp: '+pageDate);
	// console.log(pageDateParsed);
	// console.log(today);

//	if (pageDateParsed != today) {
//	// 'Mismatch of currDate and pageDate!
//	// reload navigation
//	// $.get("test.do", { pageDate:'pageDateParsed' },
//	// function(html){
//	// $('div#dateBar').emtpy().append(html);
//	// }
//	// );
//	// alert("Die Seite ist nicht mehr aktuell, bitte rufen Sie die Startseite erneut auf!")
//	} else {
//		; // NOP: currDate and pageDate match!
//	}
}

// accordion on VoD pages
function initVoDNav() {
	$('ul#vodnav li').not('li.hasSub.act').find('ul').hide();
}
function toggleVoDNav() {
	if ($(this).parent('li').hasClass('hasSub')) {
		$(this).parent('li').find('ul').slideToggle();
	}
	$(this).toggleClass('act')
}

// correctly round up the tabbed top navigation when in "'VoD' or 'Merkliste'
function fixTabs() {
	if (($('div#epg_h div#nav_main div#nav_sub').hasClass('notEPG'))
			&& ($('div#epg_h div#nav_main div#nav_sub img#nav_sub_l').attr(
					'src', '/vod/img/nav_sub_lnotEPG.png'))) {
		$('div#nav_main ul#h_grp li#tab_epg').hover(
				function() {
					$('div#epg_h div#nav_main div#nav_sub img#nav_sub_l').attr(
							'src', '/vod/img/nav_sub_lnotEPG_over.png');
				},
				function() {
					$('div#epg_h div#nav_main div#nav_sub img#nav_sub_l').attr(
							'src', '/vod/img/nav_sub_lnotEPG.png');
				});
	}
}

// show alerts when certain events occur, e.g. confirm dialogues or changes in
// the program
function hideAlerts() {
	$('body').find('div.isAlert').remove();

	if ((layerOpened == true) && (alertOpened == true)) {
		//
	} else {
		$('div#overlay').hide();
		layerOpened = false;
	}
	alertOpened = false;
}

function showAlert() {
	alertID = $(this).parents('tr').attr('id');
	alertType = $(this).parents('tr').attr('class').split(' ')[0];

	switch (alertType) {
	case ('_deleted'):
		alertMsg = 'Der Film ist nicht mehr verfügbar.';
		break;

	case ('_outdated'):
		alertMsg = 'Diese Sendung ist nicht mehr verfügbar.';
		break;
	}

	hideAlerts();

	$('body').prepend('<div class="isAlert" id="genAlert"></div>');
	$('div.isAlert#genAlert').load(
			alertUri + ' div.isAlert#genAlert div.alertCon',
			function() {
				$('div.isAlert#genAlert div.alertCon').find('div.alert_m')
						.find('p.alertMsg').empty().text(alertMsg);

				alertCSS = {
					left :(mouseX - ($('div.isAlert#genAlert').width() + 10)),
					top :(mouseY - ($('div.isAlert#genAlert').height()))
				}

				$('div.isAlert#genAlert').css(alertCSS).show();
			});

	layerOpened = true;
}

//	fix transparency issues in alerts
function fixAlerts() {
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		//	transparency fixes
		$('div.alertCon div.alert_t img.alert_tl').ifixpng();
		$('div.alertCon div.alert_t img.alert_tr').ifixpng();
		$('div.alertCon div.alert_b img.alert_bl').ifixpng();
		$('div.alertCon div.alert_b img.alert_br').ifixpng();
		
		$('div.alertCon div.alert_m a#closeAlert img').ifixpng();
	}
}

// alert entry of incorrect MasterPIN
function showAdvancedAlert() {
	winW = $(window).width();
	winH = $(window).height();

	docWidth = $(document).width();
	docHeight = $(document).height();

	overlayCSS = {
			width:winW,
			height:docHeight,
			display:'block'
	}; 
	$('div#overlay').css(overlayCSS);


	// read alert type (for Master-PIN) from URL or get it from personalization
	AdvancedAlertType = '';
	AdvancedAlertType = unescape(locSRCH);
	AdvancedAlertType = AdvancedAlertType.split("?")[1]; // string after the
															// question mark '?'

	// FIXME: URL parameters are for the server
	// if(typeof(AdvancedAlertType) != 'undefined') {
	if (false) {

		var keyVal = AdvancedAlertType.split("&"); // split string after the
													// ampersand '&'
		var isKey = new Array();
		var isVal = new Array();

		// construct key|value pairs
		for ( var i = 0; i < keyVal.length; i++) {
			isKey.push(keyVal[i].substring(0, keyVal[i].indexOf("="))); // e.g.
																		// 'pinfalse'
			isVal.push(keyVal[i].substring(keyVal[i].indexOf("=") + 1,
					keyVal[i].length)); // e.g. '2'

			// Master-PIN handling
			if (isKey[i] == 'pinfalse') {
				switch (isVal[i]) {
				case ('1'):
					alertMsg = 'Die von Ihnen angegebene PIN ist nicht korrekt. Bitte versuchen Sie es noch einmal.<br \/><br \/> Sie haben noch 4 Versuche übrig.';
					break;

				case ('2'):
					alertMsg = 'Die von Ihnen angegebene PIN ist nicht korrekt. Bitte versuchen Sie es noch einmal.<br \/><br \/> Sie haben noch 3 Versuche übrig.';
					break;

				case ('3'):
					alertMsg = 'Die von Ihnen angegebene PIN ist nicht korrekt. Bitte versuchen Sie es noch einmal.<br \/><br \/> Sie haben noch 2 Versuche übrig.';
					break;

				case ('4'):
					alertMsg = 'Die von Ihnen angegebene PIN ist nicht korrekt. Sie haben nur noch einen Versuch übrig.';
					break;

				case ('5'):
					alertMsg = 'PIN-Abfrage fehlgeschlagen. Bitte versuchen Sie es zu einem späteren Zeitpunkt noch einmal.';
					break;

				case ('locked'): // after 5 wrong entries in one session
					alertMsg = 'PIN-Abfrage fehlgeschlagen. Bitte versuchen Sie es zu einem späteren Zeitpunkt noch einmal.';
					break;
				}
			}
		}
		// hideAlerts();
		alertOpened = true;

//		console.log('layerOpened: ' + layerOpened);
//		console.log('alertOpened: ' + alertOpened);
//		console.log('isLoggedInhasHomeTv: ' + isLoggedInhasHomeTv);

		$('div#overlay').unbind('click');

		$('div#overlay')
				.show(
						function() {
							$('body')
									.prepend(
											'<div class="isAlert" id="advancedAlert"></div>');

							$('div.isAlert#advancedAlert')
									.load(
											alertUri + ' div.isAlert#advancedAlert div.alertCon',
											function() {
												// $('div.isAlert#advancedAlert').find('div.alertCon').find('div.alert_m').find('p.alertMsg').empty().html(alertMsg);

												alertH = $(
														'div.isAlert#advancedAlert')
														.height();
												alertW = $(
														'div.isAlert#advancedAlert')
														.width();

												alertY = (winH / 2)
														- (alertH / 2);
												alertX = (winW / 2)
														- (alertW / 2);

												alertCSS = {
													left :alertX,
													top :alertY
												}

												$('div.isAlert#advancedAlert')
														.css(alertCSS).show();

												if (isLoggedInhasHomeTv == 'sub') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.show()
															.css('margin-left',
																	'97px');
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
													
												}

												if (isLoggedInhasHomeTv == 'master') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.show()
															.css('margin-left',
																	'97px');

													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
												}

												if (isLoggedInhasHomeTv == 'false') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.show()
															.css('margin-left',
																	'97px');
													
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.hide();
													
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
												}

												$(
														'div.isAlert#advancedAlert a#closeAlert')
														.bind('click',
																hideAlerts);
												fixAlerts();
											});
						}).bgiframe();
	}

	else {
		// login stats, hometv stats
		if (isLoggedInhasHomeTv == 'true') {
			alertMsg = 'Die von Ihnen angegebene PIN ist nicht korrekt. Bitte versuchen Sie es noch einmal.<br \/><br \/> Sie haben noch 4 Versuche übrig.';
		}

		if (isLoggedInhasHomeTv == 'master') {
			alertMsg = 'Dieser Service steht nur den Nutzern der Fernseh-Flatrate zur Verfügung.<br \/> Sie nutzen noch nicht das digitale Film- und Fernsehvergnügen von Alice?';
		}

		if (isLoggedInhasHomeTv == 'sub') {
			alertMsg = 'Aus technischen Gründen ist ein erneuter Login erforderlich. Bitte melden Sie sich mit Ihrer Telefonnummer (Festnetz, ISDN, etc.) oder der Master E-Mail-Adresse im Alice Kundencenter an!';
		}

		if (isLoggedInhasHomeTv == 'false') {
			alertMsg = 'Dieser Service steht nur den Nutzern der Fernseh-Flatrate von Alice zur Verfügung.';
		}
	}

	if (!layerOpened) { // no
																			// details
																			// layer
																			// present
		// hideAlerts();
		alertOpened = true;

//		console.log('layerOpened: ' + layerOpened);
//		console.log('alertOpened: ' + alertOpened);
//		console.log('isLoggedInhasHomeTv: ' + isLoggedInhasHomeTv);

		$('div#overlay')
				.show(
						function() {
							$('body')
									.prepend(
											'<div class="isAlert" id="advancedAlert"></div>');

							$('div.isAlert#advancedAlert')
									.load(
											alertUri + ' div.isAlert#advancedAlert div.alertCon',
											function() {
												$('div.isAlert#advancedAlert')
														.find('div.alertCon')
														.find('div.alert_m')
														.find('p.alertMsg')
														.empty().html(alertMsg);

												alertH = $(
														'div.isAlert#advancedAlert')
														.height();
												alertW = $(
														'div.isAlert#advancedAlert')
														.width();

												alertY = (winH / 2)
														- (alertH / 2);
												alertX = (winW / 2)
														- (alertW / 2);

												alertCSS = {
													left :alertX,
													top :alertY
												}

												$('div.isAlert#advancedAlert')
														.css(alertCSS).show();

												if (isLoggedInhasHomeTv == 'sub') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.show()
															.css('margin-left',
																	'97px');
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
													
												}

												if (isLoggedInhasHomeTv == 'master') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.show()
															.css('margin-left',
																	'97px');

													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
												}

												if (isLoggedInhasHomeTv == 'false') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.show()
															.css('margin-left',
																	'97px');
													
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.hide();
													
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
												}

												$(
														'div.isAlert#advancedAlert a#closeAlert')
														.bind('click',
																hideAlerts);
												fixAlerts();
											});
						}).bgiframe();
	}

	else if (layerOpened == true) { // details layer present
		// hideAlerts();
		layerOpened = true;
		alertOpened = true;

//		console.log('layerOpened: ' + layerOpened);
//		console.log('alertOpened: ' + alertOpened);
//		console.log('isLoggedInhasHomeTv: ' + isLoggedInhasHomeTv);

		$('div#overlay')
				.show(
						function() {
							$('body')
									.prepend(
											'<div class="isAlert" id="advancedAlert"></div>');

							$('div.isAlert#advancedAlert')
									.load(
											alertUri + ' div.isAlert#advancedAlert div.alertCon',
											function() {
												$('div.isAlert#advancedAlert')
														.find('div.alertCon')
														.find('div.alert_m')
														.find('p.alertMsg')
														.empty().html(alertMsg);

												alertCSS = {
													left :(mouseX - ($(
															'div.isAlert#advancedAlert')
															.width() / 2)), // (mouseX-($('div.isAlert#ConfirmDelete').width()+10))
													top :(mouseY - ($('div.isAlert#advancedAlert')
															.height())),
													'z-index' :51
												}

												$('div.isAlert#advancedAlert')
														.css(alertCSS).show();

												if (isLoggedInhasHomeTv == 'sub') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.show()
															.css('margin-left',
																	'97px');
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
													
												}

												if (isLoggedInhasHomeTv == 'master') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.show()
															.css('margin-left',
																	'97px');

													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
												}

												if (isLoggedInhasHomeTv == 'false') {
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info')
															.show()
															.css('margin-left',
																	'97px');
													
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_info_upsell')
															.hide();
													
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_login')
															.hide();
													$(
															'div.isAlert#advancedAlert div.alert_m ul.ConfBtn li.func_infoErotic')
															.hide();
												}

												$(
														'div.isAlert#advancedAlert a#closeAlert')
														.bind('click',
																hideAlerts);
													fixAlerts();
											});
						}).bgiframe();
		
		}
}

// confirm or deny deletion of an entry
function ConfDelete() {
	// console.log('Deleted!');

	hideAlerts();

	// call function on the server and reload the page
	
	if (isLoggedInhasHomeTv == 'true') {
		btID = alertID.replace(/btEL_/g, "");
		btID = btID.replace(/btEl_/g, "");
		turn_single_note_off(btID);
		$.getJSON(NoteUrl, {
				"id" :btID,
				"action" :"remove"
			}, function(json) {
				if (!json.isSuccessful && json.errorMessageDiv) {
					displayJsonMessage(json.errorMessageDiv);
				}
		});
	}
}

function DenyDelete() {
	// console.log('Deletion denied!');

	hideAlerts();
	alertID;
	$('#' + alertID).find('a.tgl_del.act').removeClass('act');
}

// show confirmation dialogue when trying to delete an item
function delItem() {
	alertID = $(this).parents('tr').attr('id');

	if ($(this).is('.act')) {
		// already deleted!
		return;
	}
	
	$(this).addClass('act');

	alertMsg = 'Möchten Sie dieses Element <br \/>aus Ihrer Merkliste entfernen?';

	hideAlerts();

	showOverlay();
	// $('div#overlay').unbind('click');
	
	$('div#overlay')
			.show(
					function() {
						$('body')
								.prepend(
										'<div class="isAlert" id="ConfirmDelete"></div>');

						$('div.isAlert#ConfirmDelete')
								.load(
										alertUri + ' div.isAlert#ConfirmDelete div.alertCon',
										function() {
											$('div.isAlert#ConfirmDelete')
													.find('div.alertCon').find(
															'div.alert_m')
													.find('p.alertMsg').empty()
													.html(alertMsg);
											$('div.isAlert#ConfirmDelete')
													.find('div.alertCon')
													.find(
															'ul.ConfBtn li.del_yes a')
													.bind('click', ConfDelete);
											$('div.isAlert#ConfirmDelete')
													.find('div.alertCon')
													.find(
															'ul.ConfBtn li.del_no a')
													.bind('click', DenyDelete);

											alertCSS = {
												left :(mouseX + 10), // (mouseX-($('div.isAlert#ConfirmDelete').width()+10))
												top :(mouseY - ($('div.isAlert#ConfirmDelete')
														.height()))
											}

											$('div.isAlert#ConfirmDelete').css(alertCSS).show();

												fixAlerts();
										}).bgiframe();

						layerOpened = true;

					});
}

function showOverlay() {
	winW = $(window).width();
	winH = $(window).height();

	docWidth = $(document).width();
	docHeight = $(document).height();

	overlayCSS = {
		width :winW,
		height :docHeight,
		display:'block'
	}; 
	
	$('div#overlay').css(overlayCSS);
}

function gotoNow() {
	todayurl = window.location.href;
	dateNow = new Date();
	// console.log(dateNow);
	day = "" + dateNow.getDate();
	if (day.length < 2)
		day = "0" + day;
	month = "" + (dateNow.getMonth() + 1).toString();
	if (month.length < 2)
		month = "0" + month;
	year = "" + dateNow.getFullYear();
	datestring = day + month + year;
	a = todayurl.replace(/date=(\\d)*/g, "date=" + datestring + "&olddate=");
	b = a.replace(/datemax=(\\d)*/g, "datemax=" + datestring + "&olddatemax=");
	c = b.replace(/datehour=(\\d)*/g, "datehour=" + dateNow.getHours()+ "&olddatehour=");
	window.location.href = c;
}


/**
 * Quick 'n' Easy redirect function for naviation..
 */
function switchPage() {
	if (this.options[this.selectedIndex].value && this.options[this.selectedIndex].value.length > 0) {
		switchPageByUrl(this.options[this.selectedIndex].value);
	}
}

/**
 * Quick 'n' Easy redirect function for naviation..
 */
function switchPageByUrl(url) {
	showOverlay();
	$('div#overlay').addClass('invisible').css(overlayCSS);
	window.location.href = url;
}

function setCatId(categoryid) {
	$('#catid').val(categoryid);
	$('#genlist').submit();
	return false;
}

function switchToGenreView(categoryid) {
	$('#catid').val(categoryid);
	$('#catlist').submit();
	return false;
}

function switchToGenreViewListener() {
	// console.log($(this).val());
	if ($(this).val() == 0) {
		;// nop
	} else 	if ($(this).val() == 1) {
		categoryid = $('#qFilter').children()[1].value; 
		switchToGenreView(categoryid);
	} else {
		switchPageByUrl($(this).val());
	}
}

function switchGenreListener () {
	if ($(this).val()) {
		setCatId($(this).val()); 
	}
}
function switchTimeSelection() {
//	if ($('#pageDate').text() == $('#today').text()) {
//		// $('#showCurrent').addClass('act');
//		// $('#showCurrent').unbind('click');
//	}
	$('#gotoTimespan').find('option:selected').each(function(){ $(this).removeAttr("selected") });
	$('#gotoTimespan').find('option[value='+currTimeFix+']').attr("selected", "selected");
}

function showFavorites() {
	if (isPersonalizationComputed) {
		if (isLoggedInhasHomeTv) {
			if (isLoggedInhasHomeTv != 'true') {
				showAdvancedAlert();
				return false;
			} 
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function addDateTimeToUrl() {
	this.href = this.href + "&datehour=" + $('#datehourelem').val();
}

jQuery( function($) {

	try {
		console.log("Welcome to Alice Home TV...");
	} catch (e) {
		// no console availabe, maybe ie, create a console object to log
		console = function() {
		};
		console.log = function(message) {
			window.status = message;
			//alert(message);
		};
	};
	
	$('input#pinsubmit').bind('mouseover', showAdvancedAlert);


	$('a#login').find('span').text(LoginText).attr('title', LoginTitle);
	$('a#login').unbind('click');
	$('a#login').bind('click', LogMeIn); 
	
	fixTabs();
	
//	pageTime = $('#pageTime').text();
//	getDate();
//	getPageDate();

	// get the current time
	$('a#showCurrent').attr('href', '#t' + currTimeFix).bind('click', getTime);

	// set the current time with the selectbox
	$('form#jumpTimespan select#gotoTimespan').bind('change', setTime);

	// init page
	setScroll();
	setIconProps();
	setstListOlProps();

//	setZebra();
	getBtCnt();

	// hide all periods except the current one
	$('table.period').not('table.period.curr').find('tbody').hide();

	// position the station list according to the scrollOffset of the program
	// list
	$('div#scrollCon').bind('scroll', getpListO);

	// bind table handler-functions to every period's header cells
	$('table.period').not('table.period#p3').each( function() {
		$(this).find('thead tr th').bind('mouseover', activatePeriod);
		$(this).find('thead tr th').bind('mouseout', deactivatePeriod);

		$(this).find('thead tr th').bind('click', togglePeriod);
	});
	// bind table handler-functions to every period's header cells
	$('table.period#p3').children('thead tr th').bind('click',
			togglePeriodNight);

	// toggle icon behaviours
  	$(
  			'li.btIcons a.tgl_rec,table.listTable tbody tr td ul.tgl_recnote a.tgl_rec')
  			.bind('click', toggle_rec);
  	$(
  			'li.btIcons a.tgl_note,table.listTable tbody tr td ul.tgl_recnote a.tgl_note,div#vod_c div#vod_t ul li.vCover a.tgl_note,div.vWrap div.addInfo a.tgl_note')
  			.bind('click', toggle_note);

	// toggle display of details layer
  	$('.vCover')
  			.each( function() {
  				$(this).bind('click', showDetails);
  			});
  	$('.vTitle')
		.each( function() {
			$(this).bind('click', showDetails);
		});
  	
  	$('.viewTrailer')
	.each( function() {
		$(this).bind('click', showDetails);
	});

	// handle rollOvers
 	$('.hasRO').bind('mouseover', hasRO_on);
  	$('.hasRO').bind('mouseout', hasRO_off);

	// binding of accordion functions to the VoD navigation
	initVoDNav();
	$('ul#vodnav li a').bind('click', toggleVoDNav);


	// binding of alert messages to certain links
	$('table.listTable tbody tr td a.alert.act').bind('mouseover', showAlert);
	$('table.listTable tbody tr td a.alert.act').bind('mouseout', hideAlerts);

	$('a.alert').bind('mouseover', showAlert);
	$('a.alert').bind('mouseout', hideAlerts);

	// binding of confirmation dialogues to certain links
	$('table.listTable tbody tr td a.tgl_del').bind('click', delItem);

	// mousetracking
	$().mousemove( function(e) {
		mouseX = e.pageX;
		mouseY = e.pageY;
	});

	// personalize the GUI
	p13nurl = $('#p13nurl').attr('href');
	personalize();

	// ia a pagination is present, center it inside it's parent
	placePagination();
	// bind heute to gotonow
	
	$('#link_merkliste').bind('click', showReminders);

	// Login and Logout
	LoginUrl = $('#loginurl').attr('href');
	LogoutUrl = $('#logouturl').attr('href');
	NoteUrl = $('#noteurl').attr('href');
	
	RemindersUrl = $('#link_merkliste').attr('href');
	
});

/* include bgiframe fix for internet explorer 6 issues */
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-11 23:14:51 -0500 (Wed, 11 Jul 2007) $
 * $Rev: 2323 $
 *
 * Version 2.1
 */

(function($){

/**
 * The bgiframe is chainable and applies the iframe hack to get 
 * around zIndex issues in IE6. It will only apply itself in IE 
 * and adds a class to the iframe called 'bgiframe'. The iframe
 * is appeneded as the first child of the matched element(s) 
 * with a tabIndex and zIndex of -1.
 * 
 * By default the plugin will take borders, sized with pixel units,
 * into account. If a different unit is used for the border's width,
 * then you will need to use the top and left settings as explained below.
 *
 * NOTICE: This plugin has been reported to cause perfromance problems
 * when used on elements that change properties (like width, height and
 * opacity) a lot in IE6. Most of these problems have been caused by 
 * the expressions used to calculate the elements width, height and 
 * borders. Some have reported it is due to the opacity filter. All 
 * these settings can be changed if needed as explained below.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @param Map settings Optional settings to configure the iframe.
 * @option String|Number top The iframe must be offset to the top
 * 		by the width of the top border. This should be a negative 
 *      number representing the border-top-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-top-width if it is in pixels.
 * @option String|Number left The iframe must be offset to the left
 * 		by the width of the left border. This should be a negative 
 *      number representing the border-left-width. If a number is 
 * 		is used here, pixels will be assumed. Otherwise, be sure
 *		to specify a unit. An expression could also be used. 
 * 		By default the value is "auto" which will use an expression 
 * 		to get the border-left-width if it is in pixels.
 * @option String|Number width This is the width of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetWidth.
 * @option String|Number height This is the height of the iframe. If
 *		a number is used here, pixels will be assume. Otherwise, be sure
 * 		to specify a unit. An experssion could also be used.
 *		By default the value is "auto" which will use an experssion
 * 		to get the offsetHeight.
 * @option Boolean opacity This is a boolean representing whether or not
 * 		to use opacity. If set to true, the opacity of 0 is applied. If
 *		set to false, the opacity filter is not applied. Default: true.
 * @option String src This setting is provided so that one could change 
 *		the src of the iframe to whatever they need.
 *		Default: "javascript:false;"
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
$.fn.bgIframe = $.fn.bgiframe = function(sx) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		sx = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, sx || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+sx.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (sx.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(sx.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(sx.top))+';'+
					       'left:'+(sx.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(sx.left))+';'+
					       'width:'+(sx.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(sx.width))+';'+
					       'height:'+(sx.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(sx.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);