function GlobalFunctions() {
	this.findValueById = findValueById;
	function findValueById(pElement, pIdPart) {
		var level=0;
		var element = pElement;
		do {
			if(element.id && element.id.indexOf(pIdPart)==0) {
				return element.id.substring(pIdPart.length);
			} else {
				element = element.parentElement;
			}
			level++;
		} while( pElement.parentElement && level<4);
		return 'noop';
	}
}
var global = new GlobalFunctions();

var pos = 1;

function SessionManager() {
	this.setReturn = setReturn;
	this.doReturn = doReturn;
	
	var returnProc;
	var mProgId;
	
	function setReturn(ret) {
		returnProc = ret;
	}
	
	function setContentReturn(progId) {
		mProgId = progId;
		returnProc = function(){match.playContent(mProgId, true);mProgId=null};
	}

	function doReturn() {
		if (returnProc) {
			returnProc();
			returnProc = null;
		}
	}
}
var sessionManager = new SessionManager();


function Util() {
	this.logError = logError;
	this.logDebug = logDebug;
	this.error = logError;
	this.debug = logDebug;
	this.warn = logWarn;
	this.info = logInfo;
	
	this.trim = trim;
	this.isIE = isIE;
	this.isMac = isMac;
	this.isBadIE = isBadIE;
	this.isGecko = isGecko;
	this.createAlphaImg = createAlphaImg;
	this.adjustWindow = adjustWindow;
	this.readCookie = readCookie;
	this.writeCookie = writeCookie;
	this.deleteCookie = deleteCookie;
	this.backupPngFix = backupPngFix;
	this.fixPng = fixPng;
	this.restorePngFix = restorePngFix;
	this.changePngStyle = changePngStyle;
	this.isIpad = isIpad;
	
	this.tihi = tihi;
	this.fnis = fnis;
	
	
	
	
	var pngClass = 'pngTextImg';

	// no need to rerun this check during a page view
	var constIsIE = navigator.userAgent.indexOf("MSIE")>=0 && navigator.userAgent.indexOf("Opera")<0 && navigator.userAgent.indexOf("Mac")<0;
	var constIsBadIE = navigator.userAgent.indexOf("MSIE")>=0 && navigator.userAgent.indexOf("MSIE 7")<0 && navigator.userAgent.indexOf("Opera")<0 && navigator.userAgent.indexOf("Mac")<0;

	var constIsIpad = navigator.userAgent.match(/iPad/i) != null;
	
	this.Timing = Timing;
	
	function Timing() {
		var t;
		var pauseOnBenchmark = false;
		
		this.start = function() {
			t = new Date();			
		}
		
		this.benchmark = function(action) {
			try {
				info(action + ' completed after ' + (new Date().getTime() - t.getTime()) + ' ms.');
				if (pauseOnBenchmark) {
					alert('Next time will be measured from the moment you press OK.');
					t = new Date();
				}
			} catch(e) {
				logError('Util.Timing.stop',e);
			}			
		}
		
		this.enablePause = function(p) {
			pauseOnBenchmark = p;
			if (p) 
				return 'Enabling pausing for benchmarks.' 
			else 
				return 'Disabling pausing for benchmarks.';
		}
		
	}
	

	function fnis(to_enc)
	{
		var xor_key=6;
		var the_res="";//the result will be here
		for(var i=to_enc.length-1;i>=0;i--) {
			the_res+=String.fromCharCode(xor_key^to_enc.charCodeAt(i));
		}
		return the_res;
	}
	
	function tihi(to_dec)	{
		var xor_key=6;
		var the_res = '';
		for(var i=to_dec.length-1;i>=0;i--) {
			the_res+=String.fromCharCode(xor_key^to_dec.charCodeAt(i));
		}
		return the_res;
	}

		

	function trim(value) {
	   var temp = value;
	   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
	   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
	   var obj = / +/g;
	   temp = temp.replace(obj, " ");
	   if (temp == " ") { temp = ""; }
	   return temp;
	}

	function adjustWindow() {
		try {
			var cy;
			var cx;
			var iy = 600;
			var ix = 950;
			var w = 1240;
			var h = 765;
			if (document.documentElement.clientWidth == 780 || window.name.toLowerCase == 'webtv') {
				window.moveTo(0,0);
				if (window.screen.availWidth < 1270 || window.screen.availHeight < 790) {
					document.body.scroll = 'auto';
				}
				window.resizeTo(ix, iy);
				cx = ix - document.documentElement.clientWidth;
				cy = iy - document.documentElement.clientHeight;
				window.resizeTo(w + cx, h+cy);
			}
		} catch(e) {
			logError('Util.adjustWindow',e);
		}		
	}

	function logError(routine,err) { // err argument can be exception object or string
		var text;
		var type = typeof(err) + '';
		if (type.indexOf('bject') >0)
			error(routine + ': ' + err.message);
		else
			error(routine + ': ' + err);
	}
	

	function logDebug(routine,text) {
		if (text) 
			debug(routine + ': ' + text);
		else
			debug(routine);
	}

	function logWarn(routine,err) {
		var text;
		var type = typeof(err) + '';
		if (type.indexOf('bject') >0)
			warn(routine + ': ' + err.message);
		else
			warn(routine + ': ' + err);
	}

	function logInfo(routine,text) {
		if (text) 
			info(routine + ': ' + text);
		else 
			info(routine);
	}

	function isIE() { // returns false if IE for Mac
	//	logDebug('isIE', (navigator.appVersion.indexOf("MSIE")>-1) + '/' + (navigator.appVersion.indexOf("Opera")<0) + '/' + (navigator.userAgent.indexOf("Mac")<0));
		return constIsIE;
	}

	function isBadIE() { // returns true if IE 6 or lower 
		return constIsBadIE;
	}

	function isGecko() {
		return navigator.userAgent.indexOf("Gecko")>=0;
	}
	
	function isMac() {
		return navigator.userAgent.indexOf("MacOS")>=0;
	}
	
	function isIpad() {
		return constIsIpad;
	}
	

	function fixPng(elm) {
		try {
			if (constIsBadIE) {
				var realSrc = elm.src;
				if (realSrc.indexOf('.png')>0) {
					elm.setAttribute('realSrc',realSrc); // Added by tea
					var width = elm.width;
					elm.src = '/webtv/images/pixel.gif';
					// set filter
					elm.runtimeStyle.filter = "progid:DXImageTransform.Microsoft." +
								"AlphaImageLoader(src='" + realSrc + "',sizingMethod='scale')";
					if (elm.style.width.length == 0 && width > 0)
						elm.runtimeStyle.width = width + 'px';
					if (elm.style.height.length == 0 && height > 0)
						elm.runtimeStyle.height = height + 'px';
				}
				
			}
		} catch(e){logError('fixPng',e)};
	}


	function backupPngFix(elm) {
		if (isBadIE()) {
			var pngs = document.getElementsByClassName(pngClass,elm);
			var pngStyles = new Array();
			for (var i=0; i<pngs.length; i++) {
				var s = pngs[i].currentStyle.filter;
				var a = s.indexOf('http://');
				var b = s.indexOf('\',sizingMethod');
				pngStyles[i] = s.substring(a,b);
			}
			$(elm).pngStyles = pngStyles;
		}
	}

	function restorePngFix(elm) {
		if (isBadIE()) {
			var pngs = document.getElementsByClassName("pngTextImg");
			if ($(elm).pngStyles) {
				var pngStyles = $(elm).pngStyles;
				for (var i=0; i<pngStyles.length; i++) {
					pngs[i].src = pngStyles[i];
				}
			}
			//pngStyles = null;
		}
	}

	function createAlphaImg(id, src, className, style, alt) {
		if (!id) id = '';
		if (!className) className = '';
		if (!style) style = '';
		if (!alt) alt = '';	
	
		try {
			var imgHtml = '';
			if (isIE()) {
				// The correct size of the image must be defined in CSS
				imgHtml = '<div id="' + id + '" class="' + className + '" style="';
				imgHtml += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=\'scale\'); ' + style;
				imgHtml += '"></div>';				
				return imgHtml;			
			} else {
				imgHtml = '<img id="' + id + '" class="' + className + '" style="' + style + '" alt="' + alt + '" src="';
				imgHtml += src + '">';
				return imgHtml;
			}
		} catch(e) {
			logError('Util.createAlphaImg',e);
		}
	}
	
	function writeCookie(name, value, expires, path, domain, secure) {
	  logDebug('Util.writeCookie',name + '/' + value + '/' + expires + '/' + domain + '/' + secure);
	  var curCookie = name + "=" + escape(value) +
	      ((expires) ? "; expires=" + expires.toGMTString() : "") +
	      ((path) ? "; path=" + path : "") +
	      ((domain) ? "; domain=" + domain : "") +
	      ((secure) ? "; secure" : "");
	  document.cookie = curCookie;
	}

	function readCookie(name) {
	  var dc = document.cookie;
	  var prefix = name + "=";
	  var begin = dc.indexOf("; " + prefix);
	  if (begin == -1) {
	    begin = dc.indexOf(prefix);
	    if (begin != 0) return null;
	  } else
	    begin += 2;
	  var end = document.cookie.indexOf(";", begin);
	  if (end == -1)
	    end = dc.length;
	  return unescape(dc.substring(begin + prefix.length, end));
	}


	function deleteCookie(name, path, domain) {
	  if (readCookie(name)) {
	    document.cookie = name + "=" +
	    ((path) ? "; path=" + path : "") +
	    ((domain) ? "; domain=" + domain : "") +
	    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	  }
	}

	function changePngStyle(newStyle) {
		var newSrc;
		var filename;
		var style = newStyle.toLowerCase();
		var pngs = $('common').getElementsByClassName('pngTextImg', 'common');
		for( i=0;i<pngs.length;i++) {
			var currentSrc = pngs[i].src;
			// IE6 fix
			
			if (pngs[i].realSrc && currentSrc.indexOf('pixel.gif')>0) {
				currentSrc = pngs[i].realSrc;
			}
			if(currentSrc.indexOf('/' + style + '/')<0) {
				newSrc = currentSrc.substring(0,currentSrc.lastIndexOf('/')); // including style- and first letter-directories
				filename = currentSrc.substring( currentSrc.lastIndexOf('/')+1);
				newSrc = newSrc.substring(0,newSrc.lastIndexOf('/')); // including style-directory
				newSrc = newSrc.substring(0,newSrc.lastIndexOf('/')); // without style-directory
				newSrc += '/' + style + '/' + filename.charAt(0).toLowerCase() + '/' + filename;
				
				pngs[i].src = newSrc;
			}
		}
	}

}

var util = new Util();
var log = util;
util.adjustWindow();


var logError = util.logError;
var logDebug = util.logDebug;

function TileFunctions() {
	this.startRotator = startRotator;
	this.stopRotator = stopRotator;
	this.rotateTo = rotateTo;
	this.pauseRotator = pauseRotator;
	this.resumeRotator = resumeRotator;
	this.getRotatorId = getRotatorId;
	this.regGalleryEffect = regGalleryEffect;
	this.setNewsArchiveSize = setNewsArchiveSize;
	this.resizeCategoryPrograms = resizeCategoryPrograms;
	this.showNewsStaff = showNewsStaff;
	this.hideNewsStaff = hideNewsStaff;

	this.startTextFeed = startTextFeed;
	this.pauseTextFeed = pauseTextFeed;
	this.resumeTextFeed = resumeTextFeed;
	this.stopTextFeed = stopTextFeed;
	this.refreshTextFeed = refreshTextFeed;

	this.refreshTopStories = refreshTopStories;
	this.refreshTile = refreshTile;

	this.fixImage = fixImage;

	this.siteMapGoto = siteMapGoto;
	
	this.startFootball = startFootball;
	this.stopFootball = stopFootball;
	this.getCurrentMatch = getCurrentMatch;
	
	this.stop = stop;
	
	this.openTdfGallery = openTdfGallery;
	this.setTdfStage = setTdfStage;
	
	var tdfStage = '';

	var tsTimeout = 600000;
	var updater;
	var matchUpdater;
	
	var roundState;
	var tournament;
	var videoEventUpdater;

	function stop() {
		stopRotator();
		stopTextFeed();
		stopFootball();
	}

	function startFootball(tournamentId,seasonId) {
		if (!updater) {
			updater = new LiveUpdater();
			matchUpdater = new MatchUpdater();
			updater.addProcessor(matchUpdater.updateRoundState);
		} else {
			matchUpdater.resetRoundState();
		}
		/*
		if (!videoEventUpdater) {
			videoEventUpdater = new VideoEvents();
			updater.addProcessor(videoEventUpdater.updateVideoEvents)
		} else {
			videoEventUpdater.resetVideoEvents();
		}
		*/
		
		updater.startUpdater(tournamentId,seasonId);
	}

	// Traditional view, one round from specified league
	function startFootballRound(pTournamentId,pSeasonId,pRoundNo) {
		if (!tournament) {
			tournament = new Tournament(pTournamentId,pSeasonId,pRoundNo);
			tournament.createTournamentMenu();
			tournament.onRoundChange = startFootball;
		}

		if (!updater) {
			updater = new LiveUpdater();
		}
		if (!matchUpdater) {
			matchUpdater = new RoundState();
			updater.addProcessor(matchUpdater.updateRoundState);
		}
		updater.startUpdater(pTournamentId,pSeasonId,pRoundNo);
	}
	
	function stopFootball() {
		if (updater) {
			updater.stopUpdater();
		}
	}
	
	function getCurrentMatch() {
		if (matchUpdater && mainPlayer.isPlaying()) {
			var progId = mainPlayer.getProgId();
			return matchUpdater.getMatchDetails(progId);
		} else {
			return null;			
		}
	}
	
	function fixImage(img) {
		try {
			debug('Replaced missing image ...' + img.src.substring(img.src.length - 30));
		} catch(e) {
		}
		img.style.visibility = 'hidden';
	}

	function siteMapGoto(id) {
		$j('#'+id).each(function() {
			y = $j('#'+id).offset().top - $j('#siteMapList').offset().top;
			$j('#siteMapList')[0].scrollTo(y);
		});
	} 

	function refreshTopStories() {
		window.setTimeout(function(){
				if ($('topStories')) {
					userNav.openGallery('topStories');
				}
		},tsTimeout);
	}

	function refreshTile(elementId, elementUrl,checkElementId) {
		window.setTimeout(function(){
				if (!(checkElementId && !$(checkElementId)) && $(elementId)) {
					debug('Refreshing ' + elementId);
					userNav.open(elementUrl, elementId);
				} else
					debug('No refresh, ' + elementId + ' or child element gone');
			},tsTimeout);
	}

	var rotatorPE;
	var rotatorId = 0;
	var rotatorTimeout = 5;
	var delayId;
	var rotatorPaused = false;
	var rotatorDelayed = false;
	var rotatorHasList = false;
	var rotatorListLength = 5;
	
	function startRotator(hasList) {
		stopRotator();
		rotatorHasList = hasList;
		rotatorId = 0;
		if($('rotatorItem'+rotatorId)!=null && $('rotatorItem'+(rotatorId+1))) {
			debug('Start rotator');
			rotatorPE = new PeriodicalExecuter(rotate, rotatorTimeout);
		} else 
			debug('Unable to start rotator, rotatorItem0 not found');
	}
	
	function stopRotator() {
		if (rotatorPE && rotatorPE.stop)
			rotatorPE.stop();
		rotatorPE = null;
		rotatorId = 0;
	}

	function pauseRotator(delay) {
			if (delay) {
				window.clearTimeout(delayId);
				delayId = window.setTimeout(function(){resumeRotator(true)},delay*1000);
				rotatorDelayed = true;
			}
			rotatorPaused = true;
	}

	function getRotatorId() {
		return rotatorId;
	}

	function resumeRotator(delayFinished) {
		if (!rotatorDelayed || delayFinished) {
			rotatorDelayed = false;
			rotatorPaused = false;			
		}
	}

	function rotateTo(newId) {
		//if(util.isIE())
		//	window.event.cancelBubble = true;
		pauseRotator();
		var oldId = rotatorId;
		rotatorId = newId;
		
		if (newId == oldId) {
			pauseRotator(20);
			return;
		}
		// clean up last selected button
		Element.removeClassName('rotatorButton' + oldId,'selected');
		
		if (rotatorHasList) {
			Element.removeClassName('rotatorList' + oldId,'selected');
			Element.addClassName('rotatorList' + (oldId),'separated');
			if ($('rotatorList'+(oldId-1))) {
				Element.addClassName('rotatorList' + (oldId-1),'separated');
			}
		} 
		
		if ($('rotatorButton'+(oldId-1))) {
			Element.addClassName('rotatorButton' + (oldId-1),'separated');
		}
		if ($('rotatorButton'+oldId).className.indexOf('lastButton')<0) {
			Element.addClassName('rotatorButton' + (oldId),'separated');
		}
		// switch item text, if any
		if ($('rotatorText' + rotatorId)) {
			Element.hide('rotatorText' + (oldId));
			Element.show('rotatorText' + rotatorId);
		}
		
		// show new button
		Element.removeClassName('rotatorButton' + rotatorId,'separated');
		if ($('rotatorButton'+(rotatorId-1))) {
			Element.removeClassName('rotatorButton' + (rotatorId-1),'separated');
		}
		Element.addClassName('rotatorButton' + rotatorId,'selected');

		if (rotatorHasList) {
			Element.removeClassName('rotatorList' + rotatorId,'separated');
			if ($('rotatorList'+(rotatorId-1))) {
				Element.removeClassName('rotatorList' + (rotatorId-1),'separated');
			}
			Element.addClassName('rotatorList' + rotatorId,'selected');
		}
		// show item image
		if (oldId < newId) {
			debug('transition on item ' + rotatorId);
			Effect.Appear('rotatorItem'+(rotatorId), { 
					duration: 0.5,
					from: 0.0,
					to: 1.0,
					afterFinish: function(e) {
						Element.hide('rotatorItem'+(oldId));
					}
				});
		} else {
			Effect.Appear('rotatorItem'+(rotatorId), { 
					duration: 0.1,
					from: 0.0,
					to: 1.0
				});
			debug('transition on item ' + oldId + ' Is visible: ' + Element.visible('rotatorItem'+(rotatorId)));
			Effect.Appear('rotatorItem'+(oldId), { 
					duration: 0.5,
					from: 1.0,
					to: 0.0,
					afterFinish: function(e) {
						Element.hide('rotatorItem'+(oldId));
					}
				});
		}
		if (rotatorHasList) {
			var oldListStart = Math.floor(oldId/rotatorListLength)*rotatorListLength;
			var newListStart = Math.floor(newId/rotatorListLength)*rotatorListLength;
			
			for (var i=oldListStart; i<oldListStart+rotatorListLength;i++) {
				if ($('rotatorList' + i)) {
					Element.hide('rotatorList' + i);
				}
			}
			for (var j=newListStart; j<newListStart+rotatorListLength;j++) {
				if ($('rotatorList' + j)) {
					Element.show('rotatorList' + j);
				}
			}
		}
		pauseRotator(20);
	}

	function rotate() {
		try {
			if (!(rotatorPaused || mainPlayer.isPlaying())) {
				if($('rotatorItem'+rotatorId)==null) {
					debug("Rotator stopped unexpectedly");
					stopRotator();
				} else {
					rotatorId = rotatorId + 1;
					if($('rotatorItem'+rotatorId)==null) {
						//debug('Last rotator item ' + rotatorId + ', starts over again');
						Element.hide('rotatorItem'+(rotatorId-1));
						Element.removeClassName('rotatorButton' + (rotatorId-1),'selected');
						if ($('rotatorButton' + (rotatorId-2))) {
							Element.addClassName('rotatorButton' + (rotatorId-2),'separated');
						}
						if (rotatorHasList) {
							Element.removeClassName('rotatorList' + (rotatorId-1),'selected');
							if ($('rotatorList' + (rotatorId-2))) {
								Element.addClassName('rotatorList' + (rotatorId-2),'separated');
							}
						}
						rotatorId = 0;
					}
					//debug('Rotating to item ' + rotatorId);
					if (rotatorId>0) {
						if ($('rotatorText' + (rotatorId-1)))
							Element.hide('rotatorText' + (rotatorId-1));
						Element.removeClassName('rotatorButton' + (rotatorId-1),'selected');
						Element.removeClassName('rotatorButton' + (rotatorId-1),'separated');
						if (rotatorHasList) {
							Element.removeClassName('rotatorList' + (rotatorId-1),'selected');
							Element.removeClassName('rotatorList' + (rotatorId-1),'separated');
						}
					}
					if (rotatorId>1) {
						Element.addClassName('rotatorButton' + (rotatorId-2),'separated');
						if (rotatorHasList) {
							Element.addClassName('rotatorList' + (rotatorId-2),'separated');
						}
					}
					if ($('rotatorText' + rotatorId))
						Element.show('rotatorText' + rotatorId);
					Element.removeClassName('rotatorButton' + rotatorId,'separated');
					Element.addClassName('rotatorButton' + rotatorId,'selected');
	
					Effect.Appear('rotatorItem'+(rotatorId), { 
							duration: 0.5,
							from: 0.0,
							to: 1.0,
							afterFinish: function(e) {
								if (rotatorId>0) Element.hide('rotatorItem'+(rotatorId-1));
							}
						});
					
					if (rotatorHasList) {
						if ((rotatorId)%rotatorListLength ==0) {
							for (var i=rotatorId-rotatorListLength; i<rotatorId;i++) {
								if ($('rotatorList' + i)) {
									Element.hide('rotatorList' + i);
								}
							}
							for (var j=rotatorId; j<rotatorId+rotatorListLength;j++) {
								if ($('rotatorList' + j)) {
									Element.show('rotatorList' + j);
								}
							}
							Element.removeClassName('rotatorList-1','separated');
						} else {
							Element.addClassName('rotatorList-1','separated');
						}
						Element.removeClassName('rotatorList' + rotatorId,'separated');
						Element.addClassName('rotatorList' + rotatorId,'selected');
					}
				}
			}
		} catch(e) {
			logError('tiles.rotate',e);
		}
	}

	function setNewsArchiveSize(big) {
		window.setTimeout(function() {
				if (big) {
					Element.addClassName('newsArchive','enlarged');			
				} else {
					Element.removeClassName('newsArchive','enlarged');			
				}
				$j('.newsArchiveList').jScrollPane({showArrows:true, scrollbarWidth:13, arrowSize:13, scrollbarMargin: 4});
		},500);
	}

	var resizeAttempts = 0;

	function resizeCategoryPrograms() {
		if ($('categoryList') && $('categoryList').offsetHeight>0) {
			var h = 513 - ($('categoryList').offsetHeight + 50);
			$('archiveProgramsList').style.height = h + 'px';
			resizeAttempts = 0;
		} else if (resizeAttempts < 5) {
			resizeAttempts++;
			window.setTimeout(resizeCategoryPrograms,500);
		}
	}

	
	function regGalleryEffect(elm,target,dy) {
		var blindingUp = false;
		var blindingDown = false;
		var up = false;
		var currentEffect;

		try {
			Event.observe(elm, 'mouseover', onGalleryMouseOver, false);
			Event.observe(elm, 'mouseout', onGalleryMouseOut, false);
			if (!dy) {
				dy = parseInt($(target).offsetTop);
			}
			if (!dy) {
				dy = 64;				
			}
			
		} catch(e) {
			logError(e);
			
		}

		function onGalleryMouseOver(e) {
			doBlindUp();
		}
		function onGalleryMouseOut(e) {
			doBlindDown();
		}	

		function doBlindUp() {
			if (currentEffect) currentEffect.cancel();
			currentEffect = new Effect.Move(target, {y: 0, duration: 0.3, mode: 'absolute', afterFinish: function(){
					//blindingUp=false;
					//up = true;
				}} );
			//blindingUp = true;
			//blindingDown = false;
		}
		
		function doBlindDown() {
			if (currentEffect) currentEffect.cancel();
			currentEffect = new Effect.Move(target, {y: dy, duration: 0.3, mode: 'absolute', afterFinish: function(){
					//blindingDown=true;
				}} );
			//up = false;
			//blindingUp = false;
			//blindingDown = true;
		}

	}

	var tfPE = new Object();
	this.tfPE = tfPE;
	var tfId = new Object();
	var tfPaused = new Object();
	var tfItemPrefix = new Object();
	var tfRefreshAction = new Object();
	var tfPngStyle = new Object();
	var tfTimeout = 15;

	function startTextFeed(mainId,itemPrefix,refreshAction,pngStyle,delayStart) {
		tfId[mainId] = 0;
		tfItemPrefix[mainId] = itemPrefix;
		tfRefreshAction[mainId] = refreshAction;
		tfPngStyle[mainId] = pngStyle;
		if($(itemPrefix+tfId[mainId])!=null) {
			debug('Starting text feed ' + mainId);
			if (delayStart)
				window.setTimeout(function() {
						debug('Starting refresh of ' + mainId + ' with interval ' + tfTimeout + ' seconds.');
						//tfPE[mainId] = new PeriodicalExecuter(function(){refreshTextFeed(mainId)}, tfTimeout);
						tfPE[mainId] = window.setInterval(function(){refreshTextFeed(mainId)}, tfTimeout*1000);
					},Math.floor(tfTimeout*500));
			else {
				debug('Starting refresh of ' + mainId + ' with interval ' + tfTimeout + ' seconds.');
				//tfPE[mainId] = new PeriodicalExecuter(function(){refreshTextFeed(mainId)}, tfTimeout);
				tfPE[mainId] = window.setInterval(function(){refreshTextFeed(mainId)}, tfTimeout*1000);
				
			}
			Effect.Appear(itemPrefix + '0');
		} else 
			debug('Unable to start text feed ' + mainId + ', ' + itemPrefix + '0 not found');
	}

	function stopTextFeed(mainId) {
		if (!mainId) {
			debug('Stopping all text feeds');
			for (var feedId in tfId) {
				stopTextFeed(feedId);				
			}
		} else {
			//if (tfPE[mainId] && tfPE[mainId].stop) {
			//	tfPE[mainId].stop();
			if (tfPE[mainId]) {
				window.clearInterval(tfPE[mainId]);
				debug('Stopping PE for text feed ' + mainId);
			} else {
				debug('Couldn\'t stop PE for text feed ' + mainId);				
			}
			tfPE[mainId] = null;
			tfId[mainId] = 0;
			if ($(mainId))
				$(mainId).innerHTML = '';
		}
	}

	function pauseTextFeed(mainId) {
			tfPaused[mainId] = true;
	}

	function resumeTextFeed(mainId) {
			tfPaused[mainId] = false;
	}

	function refreshTextFeed(mainId) {
		if (!tfPaused[mainId]) {
			if($(mainId)==null || $(tfItemPrefix[mainId] + tfId[mainId])==null) {
				debug('Text feed ' + mainId + ' at element ' + tfItemPrefix[mainId] + tfId[mainId] + ' stopped unexpectedly');
				stopTextFeed(mainId);
			} else {
				var itemPrefix = tfItemPrefix[mainId];
				var currentId = tfId[mainId] + 1;
				if ($(itemPrefix+currentId)==null && !tfRefreshAction[mainId]) {
					// just start over again if no external refresh
					currentId = 0;
					if (!$(itemPrefix + (currentId+1))) {
						// Also, if only one item, do nothing
						return;
					}
										
					debug('Restarting ' + mainId + ' without reloading.');
				}
				
				tfId[mainId] = currentId;

				
				if($(itemPrefix+currentId)==null) {
					debug('Last ' + mainId + ' feed ' + currentId + ', needs refresh');

					Effect.Appear(itemPrefix + (currentId-1),
					{ 
						duration: 0.2,
						from: 1.0,
						to: 0.0,
						afterFinish: function(e) {
							Element.hide(itemPrefix + (currentId-1));
							stopTextFeed(mainId);
							userNav.open('ajax/' + tfRefreshAction[mainId], mainId, 'pngStyle=' + tfPngStyle[mainId]);
						}
					});

				} else {
					//debug(mainId + ' feed ' + currentId);
					Effect.Appear(itemPrefix + (currentId-1),
					{ 
						duration: 0.2,
						from: 1.0,
						to: 0.0,
						afterFinish: function(e) {
							Element.hide(itemPrefix + (currentId-1));
							//debug('Hiding ' + itemPrefix + (currentId-1));
							//debug('Showing ' + itemPrefix + (currentId));
							Effect.Appear(itemPrefix + (currentId));
						}
					});
				}
			}
		}
	}	

	function openTdfGallery(show,tab,stage) {
		if (!show && !tab && !stage) {
			$('galleryList').innerHTML = '<a href="http://drommelaget.no/tour_2007_plus" target="_blank"><img src="http://pub.tv2.no/multimedia/TV2/archive/00452/drommelaget_452893a.jpg"></a>';
			$j(function() {
				$j('#galleryTab').jScrollPane({showArrows:true, scrollbarWidth:13, arrowSize:13, scrollbarMargin: 4});
			});
		} else {
			if (stage) tdfStage = stage;
			userNav.openIframeGallery('http://pub.tv2.no/nettavisen/timeout/oneminute/TV2/tdfStatus' + tdfStage + '.html?show=' + show,tab,true);
		}
	}
	
	function setTdfStage(stage) {
		tdfStage = tdfStage;
	}


	function showNewsStaff() {
	  if (mainPlayer.isPlaying()) mainPlayer.hide();
	  var bufferFlashEmbed1 = '<object type="application/x-shockwave-flash" data="';
		var bufferFlashEmbed2 = '" id="newsStaff"><PARAM name="src" value="';
	  var bufferFlashEmbed3 = '"><PARAM name="quality" value="high"></OBJECT>';
	  var flashUrl = '/webtv/sumo/images/news/anker_oversikt.swf';
	  $('flashContainer').innerHTML = bufferFlashEmbed1 + flashUrl + bufferFlashEmbed2 + flashUrl + bufferFlashEmbed3;
	}

	function hideNewsStaff() {
	  Element.remove('newsStaff');
	  userNav.play();
	}
}
var tiles = new TileFunctions();


function TV2EffectClass() {
	this.blink = blink;

	function blink(elementId,options) {  // options: duration, period, afterFinish
		try {
			var duration = 3.0;
			var period = 0.1;
	
			var counter = 0;
			var intervalId;
			var elm = $(elementId);
			var origDisplay = elm.style.display;
			var origVisibility = elm.style.visibility;
			elm.style.display = 'block';
		
			if (options.duration) {
				duration = options.duration;
			}
			if (options.period) {
				period = options.period;
			}
			
			intervalId = window.setInterval(toggle,period * 1000);
		} catch(e) {
			logError('TV2Effect.blink',e);
		}

		function toggle() {
			counter++;
			if(counter < duration/period) {
				if (elm.style.visibility == 'hidden') {
					elm.style.visibility = 'visible';
				} else {
					elm.style.visibility = 'hidden';
				}
			} else { // finished
				clearInterval(intervalId);
				elm.style.display = origDisplay;
				elm.style.visibility = origVisibility;
				counter = 0;
				if (options.afterFinish) {
					options.afterFinish();
				}
			}
		}
	}
}


var TV2Effect = new TV2EffectClass;

