//wpntv.com tvstation update

var ShowStorage = [];
var EffectsOn = true;
var TV_MAX_VIDEO_SECTIONS = 20;

//PlayerComm
var WPNPlayerComm = new Class.create();
WPNPlayerComm.prototype ={
	stationName: "",
	initialShowID : "",
	isPlayerLoaded : false,
	autoStartPlaying : false,
	activePlayer : "",
	tvStationObj : null,
	isLinked : false,
	initialize: function( tvStationObj ){
		this.tvStationObj = tvStationObj;
		this.stationName = tvStationObj.getName();
		this.autoStartPlaying = tvStationObj.getAutoPlay();
	},
	setParametres : function(  ) {
	},
	playerLoaded : function() {
		this.isPlayerLoaded = true;
		if (this.autoStartPlaying == true) { 
			if (!this.isLinked) {
				this.playShowById( this.initialShowID );				
			} else {
				this.isLinked = false; //When we have a linked show we dont call playShowByID				
			}
		}
	},
	playingStarted: function (showId) {
	//playercallback

	},
	playingFinished: function( showId ) {
		playlist.playingFinished( showId );
	},
	playShowById: function( showId ) {	
		//if (!this.isPlayerLoaded) return; //Should allow this anyway???
		this.initialShowID = showId;
		showPlayerType = ShowStorage[showId]["showPlayerType"];
		//WPNPLAYER
		if (showPlayerType == "WPNPLAYER")	{
			if (this.activePlayer == "WPNPLAYER")  {
				obj = swfobject.getObjectById("WPNPlayer");				
				if (obj && typeof obj.playShowByID != "undefined") {	
					obj.playShowByID( showId );	
				} else {}
			} else {
				this.autoStartPlaying = true; //start playing vid
				this.renderToDiv(); //render player to DIV
			}
			return;
		}
		//youtube,googlevideo,brightcove,billabong
		if (showPlayerType == "WPNPLAYER_LIVE"|| showPlayerType == "youtube" || showPlayerType == "googlevideo" || showPlayerType == "brightcove" || showPlayerType == "billabong")  {
			this.autoStartPlaying = true;
			this.renderToDiv();
			return;
		}		
		
	},
	youtubePlayerStateChange : function ( ytPlayerState ) {
		this.isPlayerLoaded = true; //youtube player loaded OK
		//alert("ytstate:"+ytPlayerState);
		if (ytPlayerState == "0") { //player stopped after playing
			this.playingFinished( this.initialShowID );
		}
	},
	renderToDiv : function() {
		playerType = ShowStorage[this.initialShowID]["showPlayerType"];
		
		if ( playerType == "WPNPLAYER") {
			$("stream").update('<div id="player_embed"></div>');			
			this.activePlayer = playerType;
			swfobject.embedSWF("http://www.wpntv.com/common/BKDPlayer/WPNMediaPlayer.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{mode:"WPNTV",channel:this.stationName,showid:this.initialShowID,reportstatus:"true", maintainaspect:this.tvStationObj.getMaintainAspect(), acceptcommands:"true", hasintro:this.tvStationObj.isIntroEnabled() }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{name:"WPNPlayer", id:"WPNPlayer"});			
//			swfobject.embedSWF("http://www.webkast.tv/bkdplayer/BKDPlayerRelease.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{mode:"WPNTV",channel:this.stationName,showid:this.initialShowID,reportstatus:"true", maintainaspect:this.tvStationObj.getMaintainAspect(), acceptcommands:"true", hasintro:this.tvStationObj.isIntroEnabled() }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{name:"WPNPlayer", id:"WPNPlayer"});			
//			swfobject.embedSWF("http://www.wpntv.com/common/WPNPlayer.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{channel:this.stationName+".tv",showid:this.initialShowID,reportstatus:"true", maintainaspect:this.tvStationObj.getMaintainAspect(), acceptcommands:"true", hasintro:this.tvStationObj.isIntroEnabled() }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{base:"http://www.wpntv.com",name:"WPNPlayer", id:"WPNPlayer"});
//			swfobject.embedSWF("http://www.webkast.tv/common/WPNPlayer.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{channel:this.stationName+".tv",showid:this.initialShowID,reportstatus:"true", maintainaspect:this.tvStationObj.getMaintainAspect(), acceptcommands:"true" }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{base:"http://www.wpntv.com",name:"WPNPlayer", id:"WPNPlayer"});
			return;
		}
		
		if ( playerType == "WPNPLAYER_LIVE") {
			$("stream").update('<div id="player_embed"></div>');			
			this.activePlayer = playerType;
			swfobject.embedSWF("http://www.wpntv.com/common/BKDPlayer/WPNMediaPlayer.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{autoplay:"true",mode:"WPNTV",channel:this.stationName,showid:this.initialShowID, liveid:this.initialShowID , maintainaspect:this.tvStationObj.getMaintainAspect(), hasintro:this.tvStationObj.isIntroEnabled() }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{name:"WPNPlayer", id:"WPNPlayer"});									
//			swfobject.embedSWF("http://www.webkast.tv/bkdplayer/BKDPlayerRelease.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{autoplay:"true",mode:"WPNTV",channel:this.stationName,showid:this.initialShowID, liveid:this.initialShowID , maintainaspect:this.tvStationObj.getMaintainAspect(), hasintro:this.tvStationObj.isIntroEnabled() }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{name:"WPNPlayer", id:"WPNPlayer"});						
//			swfobject.embedSWF("http://www.wpntv.com/common/WPNPlayer.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{liveid:this.initialShowID, maintainaspect:this.tvStationObj.getMaintainAspect() }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{base:"http://www.wpntv.com",name:"WPNPlayer", id:"WPNPlayer"});
//			swfobject.embedSWF("http://www.webkast.tv/common/WPNPlayer.swf", "player_embed", "640", "480", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/{liveid:this.initialShowID, maintainaspect:this.tvStationObj.getMaintainAspect() }, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true"}, /*other object attribtues=*/{base:"http://www.wpntv.com",name:"WPNPlayer", id:"WPNPlayer"});
			return;
		}
		
		if ( playerType == "youtube") {
			$("stream").update('<div id="player_embed"></div>');
			this.activePlayer = playerType;
    		swfobject.embedSWF("http://www.youtube.com/v/"+ShowStorage[this.initialShowID]["showParams"]+"&enablejsapi=1&playerapiid=video&rel=0&autoplay="+(this.autoStartPlaying==true?"1":"0"), "player_embed", "640", "480", "8", null, null, { allowScriptAccess: "always"}, { id: "youtubePlayer", bgcolor:"#000000" });
		}
		
		if ( playerType == "googlevideo" ) {
			this.isPlayerLoaded = true;
			$("stream").update('<div id="player_embed"></div>');			
			this.activePlayer = playerType;			
			swfobject.embedSWF("http://video.google.com/googleplayer.swf?docId="+ShowStorage[this.initialShowID]["showParams"]+"&hl=en", "player_embed", "640", "480", "8", null, null, { subtitle:"on" }, { id: "VideoPlayback", style:"width:640px; height:480px;" });		
			return;
		}
	
		if ( playerType == "brightcove" ) {
			this.isPlayerLoaded = true;
			$("stream").update('<div id="player_embed"></div>');
			this.activePlayer = playerType;
			//FIX
			$("stream").update("<embed id='bcove' src='http://www.brightcove.tv/playerswf' bgcolor='#FFFFFF' flashVars='initVideoId="+ShowStorage[this.initialShowID]["showParams"]+"&servicesURL=http://www.brightcove.tv&viewerSecureGatewayURL=https://www.brightcove.tv&cdnURL=http://admin.brightcove.com&autoStart="+(this.autoStartPlaying==true?"true":"false")+"' base='http://admin.brightcove.com' name='bcPlayer' width='640' height='480' allowFullScreen='true' allowScriptAccess='always' seamlesstabbing='false' type='application/x-shockwave-flash' swLiveConnect='true' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'></embed>");
			
			return;
		}
		
		if ( playerType == "billabong" ) {
			this.isPlayerLoaded = true;
			$("stream").update('<div id="player_embed"></div>');
			this.activePlayer = playerType;
			
			$("stream").update('<object width="640" height="480"><param name="movie" value="http://www.billabong.com.au/video_player.swf?v='+ShowStorage[this.initialShowID]["showParams"]+'"></param><param name="allowFullScreen" value="true"></param><embed src="http://www.billabong.com.au/video_player.swf?v='+ShowStorage[this.initialShowID]["showParams"]+'" type="application/x-shockwave-flash" width="640" height="480" allowFullScreen="true"></embed></object>');
			return;
		}
	
		
	},
	renderToDivForShowID : function(showID) {
		this.initialShowID = showID;
		this.renderToDiv();
	}
};

//Youtube player callback
function onYouTubePlayerReady(playerId) {
	obj = swfobject.getObjectById("youtubePlayer");				
		if (obj) {			
			obj.addEventListener("onStateChange","youtubePlayerStateChange");			
		} else {/*err*/}  
}



var ShowStorageControl = new Class.create();
ShowStorageControl.prototype={
	initialize : function (){
	},
	newShow : function(showID, showHasSnapshot, showSection, showDateCreated, showDescription, showTitle, showFilename, showCommentsNum, showRating, showDuration, showViews) {
		if (Object.isUndefined(ShowStorage[showID])){
			this.updateShow(showID, showHasSnapshot, showSection, showDateCreated, showDescription, showTitle, showFilename, showCommentsNum, showRating, showDuration, showViews);
		} else {/*show already in cache*/}
	},
	updateShow : function (showID, showHasSnapshot, showSection, showDateCreated, showDescription, showTitle, showFilename, showCommentsNum, showRating, showDuration, showViews) {
			ShowStorage[showID] = [];
			ShowStorage[showID]['showID'] = showID;
			ShowStorage[showID]['showHasSnapshot'] = showHasSnapshot;
			ShowStorage[showID]['showSection'] = showSection;
			ShowStorage[showID]['showDateCreated'] = showDateCreated;
				if (showDateCreated.indexOf("1970") != -1) {
						ShowStorage[showID]['showDateCreated'] = ""; //if there was no date created set (erased) we dont show it.
				}
			ShowStorage[showID]['showDescription'] = showDescription;
			ShowStorage[showID]['showTitle'] = showTitle;
			ShowStorage[showID]['showCommentsNum'] = showCommentsNum;
			ShowStorage[showID]['showRating'] = showRating;
			ShowStorage[showID]['showParams'] = "none";
			ShowStorage[showID]['showDuration'] = showDuration;
			ShowStorage[showID]['showPlayerType'] = "WPNPLAYER";
			ShowStorage[showID]['showShowViews'] = showViews;
			if (showFilename.indexOf('WPNPLAYER_LIVE:') != -1 || showFilename.indexOf('youtube:') != -1 || showFilename.indexOf('brightcove:') != -1 || showFilename.indexOf('googlevideo:') != -1 || showFilename.indexOf('billabong:') != -1 ) {
				Try.these(
					function() {
						params = showFilename.split(':');						
						ShowStorage[showID]['showParams'] = params[1];
						ShowStorage[showID]['showPlayerType'] = params[0];												
					}.bind(showFilename).bind(showID)
				);				
			} 
	},
	setShowInPlaylistState : function ( showID, isInPlaylist ) {
		if (Object.isUndefined(ShowStorage[showID])){
			ShowStorage[showID]['playlist'] = isInPlaylist;
		}
	},
	isShowInPlaylist : function ( showID ) {
		if (Object.isUndefined(ShowStorage[showID])){
			if (Object.isUndefined(ShowStorage[showID]['playlist'])) {
				return ShowStorage[showID]['playlist'];
			}
		}
		return false;
	},
	updateShowByXMLNode : function ( showNode, doUpdateIfExists /*=true/false*/ ) {
		showID = showNode.getAttribute('ID');
		showHasSnapshot = showNode.getAttribute("hasSnapshot");
		showSection = ""; //showNode.getAttribute('section').escapeHTML();
		showDateCreated = showNode.getAttribute('created').escapeHTML();
		showTitle = showNode.getElementsByTagName('showname')[0].childNodes[0].nodeValue.escapeHTML();
		showDescription = (showNode.getElementsByTagName('description')[0].childNodes.length>0?showNode.getElementsByTagName('description')[0].childNodes[0].nodeValue.escapeHTML():'');
		showDuration = "";
		showViews = "0";//showNode.getAttribute('showViews');
		showFilename="";
		showCommentsNum = "0";
		showRating = "0";
		Try.these(function() {
					showFilename = showNode.getElementsByTagName('files')[0].getElementsByTagName('file')[0].getElementsByTagName('filename')[0].childNodes[0].nodeValue;
						//ShowStorage[showID]["showParams"]=showFilename;	
				  }.bind(showNode).bind(showFilename));		
		Try.these(function() {
							showDurationSeconds = showNode.getElementsByTagName('files')[0].getElementsByTagName('file')[0].getElementsByTagName('length')[0].childNodes[0].nodeValue;
							if (showNode.getElementsByTagName('files')[0].getElementsByTagName('file').length > 1) {
									showDurationSeconds = parseInt(showDurationSeconds) + parseInt(showNode.getElementsByTagName('files')[0].getElementsByTagName('file')[1].getElementsByTagName('length')[0].childNodes[0].nodeValue);
							}
							minutes = parseInt(showDurationSeconds / 60);
							seconds = parseInt(showDurationSeconds % 60);							
							if (showDurationSeconds == "-1") 
							{ 
								showDuration="";
							} else {
								showDuration = minutes+":"+(seconds<10?'0':'')+seconds;
							}
				  }.bind(showNode).bind(showDuration));
		if (doUpdateIfExists == true) {
			this.updateShow(showID, showHasSnapshot, showSection, showDateCreated, showDescription, showTitle,showFilename, showCommentsNum, showRating, showDuration, showViews);
		} else {
			this.newShow(showID, showHasSnapshot, showSection, showDateCreated, showDescription, showTitle,showFilename, showCommentsNum, showRating, showDuration, showViews);
		}
		return showID;
	}
};
var showStorageControl = new ShowStorageControl();

var Player = Class.create();
Player.prototype = {
	initialize : function( tvStationObj ) {
		
	},
	playShowByID : function ( showID ) {
		
	}
};

var Playlist = Class.create();
Playlist.prototype = {
	xml : '/xml/smallwebkast.xml',
	startupXML : '/xml/startup.xml',
	liveXML : '/xml/live.xml',
	selectedVideoSection : '',
	selectedShow : '',
	selectedShowVideoSection:'',
	searchScriptLocation:'/common/videobrowser/scripts/archive.php',
	//videosections : [],
	initialize : function( tvStationObj ) {
		this.videoSections = [];
		this.videoSectionNames = [];
		this.tvStationObj = tvStationObj;
		if (tvStationObj.getLiveStreamEnabled() == true) {
			this.loadLiveXML();	//load live.xml then build playlist
		} else {
			this.buildPlaylist(); //skip loading live.xml
		}
	},
	buildPlaylist : function() {
		if (this.tvStationObj.getShowActualSection() == true) {
			this.loadStartupXML(); //load startup.xml (last 20 shows) into actual section
		}
		else {
			this.loadSmallWebkast(); //skip startup.xml, just load playlists
		}		
	},
	liveStreams : null,
	loadLiveXML : function() {
			new Ajax.Request(this.liveXML+RND.getURLRND(), {
									method:'get',
									contentType : 'application/xml',
									onSuccess : function( data ) {
											//LOAD LIVE STREAMS (live.xml)
											xmlResponse = data.responseXML;
											this.liveStreams=[];
											streamsNode = xmlResponse.getElementsByTagName("streams")[0].getElementsByTagName('stream');		
											idx=0;									
											for (i=0; i < streamsNode.length; i++) {
												if (streamsNode[i].getAttribute("active") == "true") {
													this.liveStreams[idx] = [];
													this.liveStreams[idx]["id"] = streamsNode[i].getAttribute("id");
													this.liveStreams[idx]["title"] = streamsNode[i].getAttribute("title");
													this.liveStreams[idx]["description"] = streamsNode[i].getAttribute("description");
													this.liveStreams[idx]["active"] = streamsNode[i].getAttribute("active");
													showStorageControl.newShow(streamsNode[i].getAttribute("id"), false, "showSection", streamsNode[i].getAttribute("description"), "", streamsNode[i].getAttribute("title"), "WPNPLAYER_LIVE:" + streamsNode[i].getAttribute("id"), "", "", "", "");
													idx++;
												}
											}
											this.buildPlaylist();
									}.bind(this) 												  
						  });
	},
	loadStartupXML : function() {
		//load startup xml -> Actual section, then load webkast
		new Ajax.Request(this.startupXML+RND.getURLRND(), {
									method:'get',
									contentType : 'application/xml',
									onSuccess : function( data ) {
											//LOAD startup.xml
											xmlResponse = data.responseXML;
											showsNode = xmlResponse.getElementsByTagName('browser')[0].getElementsByTagName('shows')[0].getElementsByTagName('show');
											this.videoSections[0] = [];
											this.videoSectionNames[0] = Locale["actual"];											
											startIndex=0;
											if (this.tvStationObj.getLiveStreamEnabled() == true) {
												for (i=0; i<this.liveStreams.length; i++) {
													this.videoSections[0][i] = this.liveStreams[i]["id"];
												}
												startIndex = this.liveStreams.length;
											}	

											for (i=0+startIndex; i < showsNode.length+startIndex; i++) {
												
													showStorageControl.updateShowByXMLNode(showsNode[i-startIndex], false);
													this.videoSections[0][i] = showsNode[i-startIndex].getAttribute("ID");																								
											}
											this.loadSmallWebkast();		
									}.bind(this) 																  
						  });
	},
	loadSmallWebkast : function() {
		new Ajax.Request(this.xml+RND.getURLRND(), {
									method:'get',
									contentType : 'application/xml',
									onSuccess : function( data ) {
											xmlResponse = data.responseXML;
											startIndex = this.videoSections.length; //if we push in before "actual" section , video section indexes go up by 1											
											for (i = 0 + startIndex; (i < xmlResponse.getElementsByTagName('TVStation')[0].getElementsByTagName('videoprogram').length + startIndex) && ( i < TV_MAX_VIDEO_SECTIONS ) ; i++) {
												videoprogram_node = xmlResponse.getElementsByTagName('TVStation')[0].getElementsByTagName('videoprogram')[i-startIndex]; 
												this.videoSections[i] = [];
												this.videoSectionNames[i] = videoprogram_node.getAttribute("name");												
												startShowIndex=0; //relative index to injected live streams;-)
												if (this.tvStationObj.getLiveStreamEnabled() == true && i == startIndex) { /* in first section we push in active live streams*/
													for (k=0; k<this.liveStreams.length; k++) {
														this.videoSections[i][k] = this.liveStreams[k]["id"];
													}
													startShowIndex = this.liveStreams.length;
												}													
												for (j = 0; j < videoprogram_node.getElementsByTagName('filler')[0].getElementsByTagName('shows')[0].getElementsByTagName('show').length; j++) {
													showNode = videoprogram_node.getElementsByTagName('filler')[0].getElementsByTagName('shows')[0].getElementsByTagName('show')[j];
													showStorageControl.updateShowByXMLNode(showNode, false);
													this.videoSections[i][j+startShowIndex] = showNode.getAttribute("ID");												
												}
											}
											//FIRE UP PLAYER
											/*this.selectedVideoSection = 0;
											this.selectedShow = Math.floor(Math.random()*this.videoSections[this.selectedVideoSection].length);
											this.selectedShowVideoSection = 0;
											this.renderPlaylist(true); // == SELECT SHOW
											this.renderTabs();
											this.playShowByID(this.selectedShow);						*/
											
											this.fireUpPlayer();
									}.bind(this) 																  
						  });
	},
	fireUpPlayer : function() {
		if (this.tvStationObj.getQueryParams() != null) {
			// load show info and render player
			showID = this.tvStationObj.getQueryParams()["showid"];
			showidentifier = showID; //little workaround for binding in ajax request
			new Ajax.Request(this.searchScriptLocation+'?TVStation='+this.tvStationObj.getName()+'&action=getResultSet&search='+showID+RND.getURLRNDPostFix(), {
							method:'get',
							contentType : 'application/xml',
							onSuccess : function( data ) {							
								xmlResponse = data.responseXML;		
								gotMatch = false;				
								if (xmlResponse.getElementsByTagName('SearchResult')[0].getElementsByTagName('show').length > 0)
								{
									showNode = xmlResponse.getElementsByTagName('SearchResult')[0].getElementsByTagName('show')[0];								
									showID = showStorageControl.updateShowByXMLNode(showNode,false);
									if (showID == showidentifier) {
										player.isLinked = true;
										playlist.playShowBySHOWID(showID);										
										gotMatch = true;
									} 
								}
								if (!gotMatch) {
									//ce ni v search requestu je morda live stream
									if (this.liveStreams != null) {
										for (i = 0; i < this.liveStreams.length; i++) {
											if (this.liveStreams[i]["id"] == showidentifier) {
												player.isLinked = true;
												playlist.playShowBySHOWID(showidentifier);
												gotMatch = true;
											}
										}
										this.displayErrorLoadingShowByID();
									}
									if (!gotMatch) {
										//video ki ste ga zahtevali ni bil najden
										this.displayErrorLoadingShowByID();
									}
								}
							}.bind(this).bind(showidentifier)
				  });
		} 
		this.selectedVideoSection = 0;
		if (this.tvStationObj.getRandomShowOnStartup() == true ) {
			this.selectedShow = Math.floor(Math.random() * this.videoSections[this.selectedVideoSection].length);
		} else {			
			this.selectedShow = 0;
		}
		if (this.tvStationObj.getQueryParams() == null) {
			//TEHRE IS NO ?show=...
			this.selectedShowVideoSection = 0;
			this.renderPlaylist(true); // == SELECT SHOW
			this.renderTabs();
			this.playShowByID(this.selectedShow);			
		} else {
			this.selectedShowVideoSection = 0;
			this.renderPlaylist(true); // == SELECT SHOW
			this.renderTabs();			
		//	this.playShowByID(this.selectedShow);						
		}			
	},
	displayErrorLoadingShowByID : function() {
		$("banner").update("Requested show was not found or isn't available at the moment.");		
	},
	selectShow : function(playlistIndex, showIndex) {
		this.selectedShowVideoSection = playlistIndex;
		this.selectedShow = showIndex;
	},

	renderPlaylist : function( doAnimate ) {
		if (doAnimate) {
			$('program_content').hide();
		}
		output = "<ul>";
		for ( i=0; i < this.videoSections[this.selectedVideoSection].length; i++) {
			showID = this.videoSections[this.selectedVideoSection][i];
			if ( i == this.selectedShow && this.selectedVideoSection == this.selectedShowVideoSection) {
				output = output + '<li class="selected_item">  <table class="program_tabela"><tbody><tr> <td class="program_tabela_slika"><img width="70" height="52" src="media/'+showID+'.jpeg"/></td><td class="program_tabela_tekst"><span class="program_naslov">'+ShowStorage[showID]["showTitle"]+'</span><br/><p class="gumbi"><img width="49" height="14" src="common/onair1.png" class="prozorno"/></p><p><span id="fillerDescription0" class="program_opis"/></p></td></tr></tbody></table></li>';
			} else {
				output = output + '<li><table class="program_tabela"><tbody><tr> <td class="program_tabela_slika"><img width="70" height="52" src="media/'+showID+'.jpeg"/></td><td class="program_tabela_tekst"><span class="program_naslov">'+ShowStorage[showID]["showTitle"]+'</span><br/><p class="gumbi"><a href="javascript:playlist.playShowByID(\''+i+'\')"><img width="49" height="14" src="common/play2.png" class="prozorno" name="btnplayfiller1"/></a> '+(ShowStorage[showID]["showDescription"].length>0?'<a  href="javascript:playlist.showDescription(\''+i+'\')"><img width="49" height="14" alt="Info" src="common/info2.png" class="prozorno" name="btninfofiller1"/></a>':'')+' </p><p><span id="description_'+i+'" class="program_opis" style="display:none">'+modules.parseDescription(ShowStorage[showID]["showDescription"])+'</span></p></td></tr></tbody></table></li>';								
			}
		}
		output = output + "</ul>";
		$('program_content').update(output);
		if (doAnimate) {
			if (EffectsOn==true)
				//new Effect.SlideDown('program_content',{duration:0.5});
				new Effect.Appear('program_content',{duration:0.5});
			else 
				$('program_content').show();
		}
	},
	oldIndex : '-1',
	showDescription : function( index ) {
		Try.these( function() {
			$('description_'+this.oldIndex).hide();
		}.bind(this));
		if (this.oldIndex != index) {
			Try.these( function() {
				if (EffectsOn==true) {
					new Effect.Appear('description_'+index,{duration:0.5});
				} else
					$('description_'+index).show();
				this.oldIndex = index;
			}.bind(this));		
		} else {
			this.oldIndex = -1;
		}
	},
	visibleTabsIndex : 0,
	shiftTabsLeft : function() {
		if (this.visibleTabsIndex > 0) {
			this.visibleTabsIndex--;
			this.renderTabs();
		}
	},
	shiftTabsRight : function() {
		if (this.visibleTabsIndex < this.videoSections.length - 3) {
			this.visibleTabsIndex++;
			this.renderTabs();
		}
	},
	renderTabs : function() {
		output = "<ul>";
		for ( i = this.visibleTabsIndex; i < this.visibleTabsIndex + 3 && i < this.videoSectionNames.length; i++ ) {
			output = output + "<li>";
				output = output + '<a '+(i==this.selectedVideoSection?'class="current"':'')+' href="javascript:void(0);" '+(i==this.selectedVideoSection?'':'onclick="javascript:playlist.selectTab(\''+i+'\');"')+'><span>'+this.videoSectionNames[i].truncate(this.tvStationObj.getMaxTVVideoSectionChars())+'</span></a>';
			output = output + "</li>";
		}
		output = output + "</ul>";
		$('tabs').update(output);
	},
	selectTab : function ( videoSectionIndex ) {
		this.selectedVideoSection = videoSectionIndex;
		this.renderTabs();
		this.renderPlaylist(true);
	},
	lastPlayedShowIndex : 0,
	lastPlayedShowVideoSectionIndex : 0,
	playShowByID : function ( index ) {
		this.lastPlayedShowIndex = index;
		this.lastPlayedShowVideoSectionIndex = this.selectedVideoSection;
		showId = this.videoSections[this.selectedVideoSection][index];
		player.playShowById( showId  );
		this.displayShowInfo( showId );
		this.selectedShow = index;
		this.selectedShowVideoSection = this.selectedVideoSection;
		this.renderPlaylist(false);
		//update Module embed
		this.currentShowID = showId;
		Try.these( function() {
			modules.updateShowInfo();
		}.bind(showId));
	},
	playShowBySHOWID : function( showId ) {
		this.lastPlayedShowIndex = -1;
		this.lastPlayedShowVideoSectionIndex = this.selectedVideoSection;
		player.playShowById( showId  );		
		this.displayShowInfo( showId );
		this.selectedShow = -1;
		this.selectedShowVideoSection = this.selectedVideoSection;
		this.renderPlaylist(false);
		this.currentShowID = showId;
		Try.these( function() {
			modules.updateShowInfo();
		}.bind(showId));		
	},
	playingFinished : function ( showID ) {
		this.lastPlayedShowIndex++;
		if (this.lastPlayedShowIndex > this.videoSections[this.lastPlayedShowVideoSectionIndex].length - 1) {
			this.lastPlayedShowIndex = 0;			
		}
		player.playShowById( this.videoSections[this.lastPlayedShowVideoSectionIndex][this.lastPlayedShowIndex] );
		this.selectedShow = this.lastPlayedShowIndex;
		this.renderPlaylist(false);
	},
	displayShowInfo : function ( showID ) {
		$('playing_content').update('<table class="playing_tabela"><tbody><tr> <td class="playing_slika"><div id="playing_slika_div"><img width="119" height="88" src="media/'+showID+'.jpeg"/></div></td><td><div id="playing_vsebina"><span class="playing_naslov" id="playing_naslov">'+ShowStorage[showID]["showTitle"]+'</span><br/><br/><span class="playing_opis" id="playing_opis">'+modules.parseDescription(ShowStorage[showID]["showDescription"])+'</span><br/><br/><span class="playing_trajanje" id="playing_trajanje">'+ShowStorage[showID]["showDuration"]+'</span><br/><br/><span class="playing_ponavljanja" id="playing_ponavljanja"/></div></td></tr></tbody></table>');
	},
	currentShowID : "-1",
	getCurrentlyPlayingShowID : function () {
		return this.currentShowID;
	},
	getCurrentlyPlayingShowDescription : function () {
		return ShowStorage[this.currentShowID]["showDescription"];
	}
};

/*
	Random number generator (helps with page refresh in IE browsers)
*/
var RandomGenerator = Class.create();
RandomGenerator.prototype={
	initialize : function() {
	},
	getURLRND : function() {
		return '?RND='+Math.random();
	},
	getURLRNDPostFix : function() {
		return '&RND='+Math.random();
	}
};
RND = new RandomGenerator;

var AdsControl = Class.create();
AdsControl.prototype = {
	tvStationObj : null,
	request : '/common/videobrowser/scripts/getAd.php',
	initialize : function( tvStationObj ) {
		this.tvStationObj = tvStationObj;
		//this.getAd();
	},
	getAd : function() {
		new Ajax.Request(this.request+'?TVStation='+this.tvStationObj.getName()+"&uitype=normal",
						 {
							 method : 'get',
							 contentType : 'application/xml',
							 onSuccess : function( data ) {		
								xmlResponse = data.responseXML;																
								adType = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("type");							
								adID = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("ID");
								if (adType=="flash") {
									adLink = ""; //cant handle flash click
									adFilename = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("filename");
									adLink = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("link");
									//TODO: read flashParams, read flashVars
									this.renderFlashAd( adFilename, adLink );
								}
								if (adType=="image") {
									adLink = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("link");
									adFilename = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("filename");
									this.renderImageAd( adFilename, adLink, adID );
								}
								if (adType=="embed") {
									embedCode = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("embedCode");
									this.renderEmbedAd( embedCode/*.unescapeHTML()*/ );
								}
								if (adType =="ext") {
									adLink = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("link");
									adFilename = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("filename");
									sourceType = xmlResponse.getElementsByTagName('Ad')[0].getAttribute("sourceType");
									if (sourceType == "IMG") {
										this.renderImageAd(adFilename, adLink, adID);
									} else if (sourceType == "SWF") {
										this.renderFlashAd( adFilename, adLink);
									}
								}

							 }.bind(this)
						 });
	},
	renderFlashAd : function( flashUrl, adLink ) {
		$('modules_content').update('<div id="flashBanner"></div>');
		//swfobject.embedSWF(flashUrl, "flashBanner", "340", "269", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/false, /*flashParams=*/false, /*other object attribtues=*/false);
		swfobject.embedSWF("/common/util/swf/ad/WPNFlashAd.swf?swfSource="+flashUrl+"&swfTarget="+adLink, "flashBanner", "500", "160", "9.0.0", /*expressInstallLink=*/false, /*flashVars=*/false, /*flashParams=*/false, /*other object attribtues=*/false);
	},
	renderImageAd : function( imageUrl, linkUrl , adID) {
		$('modules_content').update('<a target="_blank" href="'+linkUrl+'" onclick="javascript: adsControl.adHit(\''+adID+'\');"><img border="0" src="'+imageUrl+'" /></a>');
	},
	renderEmbedAd : function( embedCode ) {
		$('modules_content').update( embedCode ); //UNESCAPE HTML, VULNERABILITY!!!!
	},
	adHit : function ( adID ) {
		new Ajax.Request(this.request+'?TVStation='+this.tvStationObj.getName()+'&action=vote&adID='+adID,{ method : 'get' } );	
	}
};


var Modules = Class.create();
Modules.prototype = {
	tvStationObj : null,
	newsXML : '/xml/news.xml',
	searchScriptAddress : '/common/videobrowser/scripts/archive.php',
	emailScript : '/common/sendmail.php',
	selectedModule : '',
	initialize : function( tvStationObj ) {
		this.tvStationObj = tvStationObj;
		this.modules = tvStationObj.getModules();
		//this.renderTabs( -1 );
		this.renderModuleByName( tvStationObj.getStartupModule() );
	},
	renderTabs : function( selected ) {
		output = '<ul id="menux">';
		for ( i = 0; i < this.modules.length; i++) {
			if ( i == selected) {
				output = output + "<li><a href=\"javascript:void(0);\" class=\"current\">"+this.getModuleTitle(this.modules[i])+"</a></li>";
			} else
				output = output + "<li><a href=\"javascript:void(0);\" onclick=\"javascript:modules.renderModule('"+i+"')\">"+this.getModuleTitle(this.modules[i])+"</a></li>";
		}
		output = output + "</ul>";
		$("modules_menu").update(output);
	},
	getModuleTitle : function( title ) {
//		return "module_"+title;
		if (title == "customLink") {
			return this.tvStationObj.getCustomLinkName();
		}
		return Locale["module_"+title];
	},
	renderModuleByName : function ( moduleName ) {
		for (i=0; i < this.modules.length+1; i++) {
			if (moduleName == this.modules[i]) {
				this.renderModule(i);
				break;
			}
		}
	},
	updateShowInfo : function(  ) {
		if (this.selectedModule == "embed") {
			showID = playlist.getCurrentlyPlayingShowID();
			Try.these(function() {
				$("playerInfo_LinkValue").setValue("http://"+this.tvStationObj.getName()+".tv/?showid="+showID);
				if (ShowStorage[showID]["showPlayerType"] == "WPNPLAYER") {
//	Old Embed:			$("playerInfo_EmbedValue").setValue("<embed src='http://www.wpntv.com/common/WPNPlayer.swf' bgcolor='#FFFFFF' flashVars='channel="+this.tvStationObj.getName()+".tv&showid="+showID+"' base='"+this.tvStationObj.getAddress()+"' name='WPNPlayer' width='640' height='480'  allowFullScreen='true'  seamlesstabbing='false' type='application/x-shockwave-flash' swLiveConnect='true' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'></embed>");				
	
				$("playerInfo_EmbedValue").setValue('<object width="640" height="480"><param name="movie" value="http://wpntv.com/common/bkdplayer/?station='+this.tvStationObj.getName()+'&showid='+showID+'"></param><param name="allowFullScreen" value="true"></param>				<param name="allowscriptaccess" value="always"></param>	<embed src="http://wpntv.com/common/bkdplayer/?station='+this.tvStationObj.getName()+'&showid='+showID+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="480"></embed></object>');				
	
				} else {
					$("playerInfo_EmbedValue").setValue("Embed koda za ta posnetek ne obstaja.");
				}
				
			}.bind(this));
		}
		if (this.selectedModule == "downloadlink") {
			description = playlist.getCurrentlyPlayingShowDescription();
			title = ShowStorage[playlist.getCurrentlyPlayingShowID()]["showTitle"];
			Try.these(function() {	
				linkPos = description.lastIndexOf('[Download:');
				if (linkPos >= 0) {
					linkEnd = description.indexOf(']',linkPos);
					extractedLink="";
					if (linkEnd > 0) {
						extractedLink = description.substring(linkPos + 10, linkEnd);
						$("downloadLinkHolder").update('To download video file for '+title+' click <a target="_blank" href="'+extractedLink+'">HERE</a>.');
					} else {
						$("downloadLinkHolder").update("Download not available.");
					}
				} else {
					$("downloadLinkHolder").update("Download not available.");					
				}
			}.bind(this),
			function() {
				$("downloadLinkHolder").update("Download not available.");
			}			
			);
		}
	},
	execSearch : function() {
//		alert("search for "+$("searchBox").value);
		//TODO : ajax request for search, display results
		searchString = $("searchBox").value;
		new Ajax.Request(this.searchScriptAddress+'?TVStation='+this.tvStationObj.getName()+'&action=getResultSet&numRecords=20&startRecord=0&search='+searchString+RND.getURLRNDPostFix(),
						 {
							 method : 'get',
							 contentType : 'application/xml',
							 onSuccess : function( data ) {
							 	generatedResults = "<br/><br/>Rezultati: <br/><br/>";
								xmlResponse = data.responseXML;																
								numHits = xmlResponse.getElementsByTagName('SearchResult')[0].getAttribute("NumResult");																		
								for ( i=0; i < xmlResponse.getElementsByTagName('SearchResult')[0].getElementsByTagName('show').length; i++) {
									
									showNode = xmlResponse.getElementsByTagName('SearchResult')[0].getElementsByTagName('show')[i];
									showID = showStorageControl.updateShowByXMLNode(showNode,false);									
									//TODO FIX!:)
									showHasSnapshot = showNode.getAttribute("hasSnapshot");									
									showSection = showNode.getAttribute('section').escapeHTML();									
									showDateCreated = showNode.getAttribute('created').escapeHTML();
									if (showDateCreated.indexOf("1970") != -1) { showDateCreated=""; }
									showTitle = showNode.getElementsByTagName('showname')[0].childNodes[0].nodeValue.escapeHTML();
									
									//tempEntry = showTitle+" <br/>";
									tempEntry = "<hr/><br/><h2>"+showTitle+"</h2><p>"+ShowStorage[showID]["showDescription"]+"</p>";
									tempEntry = tempEntry + "<p class=\"gumbi\"><a href=\"javascript:playlist.playShowBySHOWID('"+showID+"')\"><img class=\"prozorno\" width=\"49\" height=\"14\" src=\"/common/play2.png\"/></a></p><br/>";
									
									generatedResults = generatedResults + tempEntry;
								}
								if (numHits == "0") { generatedResults = generatedResults + "Ni zadetkov."; }								
								$('searchResults').update(generatedResults);
							 }.bind(this)
						 });
		
	},
	renderModule : function( moduleIndex ) {		
		moduleName = this.modules[ moduleIndex ];
		this.selectedModule = moduleName;
		this.renderTabs( moduleIndex );
		if (moduleName == "search") {
			
			$("modules_content").update('<form action="javascript:modules.execSearch()"> Iskani niz: <input type="text" size="40" id="searchBox" name="searchBox"/> <input type="submit" value="Iskanje"/> </form><div id="searchResults"></div>');			
			
		} else
		if (moduleName == "embed" ) {
			$("modules_content").update('<center><br/><br/><span id="videoLinkHolder"> <span id="videoLink">Povezava do videa: </span><input style="width:330px;" id="playerInfo_LinkValue" name="playerInfo_LinkValue" type="text" class="linkBox" onClick="javascript:this.focus();this.select();" value=""/> </span><br/><br/><span id="embedHolder"><span id="embedText">Embed koda:</span> <input style="width:240px;" id="playerInfo_EmbedValue" name="playerInfo_EmbedValue" type="text" class="linkBox" onClick="javascript:this.focus();this.select();" value=""/></span></center>');
			this.updateShowInfo();
		} else
		if (moduleName == "videobrowser") {
			window.location="http://www."+this.tvStationObj.getName()+".tv/browser/";
			//window.open( "/browser/", "browser", "" );
		} else
		if (moduleName == "ads") {
			//$("modules_content").update(Locale["adPlaceholder"]);
//					$('ad_placeholder').update('<div id="flashBanner"></div>');
			$("modules_content").update("");
			adsControl.getAd();
		} else
		if (moduleName == "upload") {
			//window.open( "/common/uploadForm/uploadForm.php?tvStation="+this.tvStationObj.getName(), "uploadFromWindow", "status = 1, height = 620, width = 460, resizable = 0" );
			this.showUploadForm();
		} else 
		if (moduleName == "news") {
			new Ajax.Request(this.newsXML+RND.getURLRND(), {
										method:'get',
										contentType : 'application/xml',
										onSuccess : function( data ) {
												$("modules_content").hide();
												$("modules_content").update("");
												
												xmlResponse = data.responseXML;
												for (i=0; i < xmlResponse.getElementsByTagName('news')[0].getElementsByTagName('story').length; i++) {
													newsNode = xmlResponse.getElementsByTagName('news')[0].getElementsByTagName('story')[i];
													
													title = (newsNode.getElementsByTagName('title').length>0?newsNode.getElementsByTagName('title')[0].childNodes[0].nodeValue:"");
													time = (newsNode.getElementsByTagName('time').length>0?newsNode.getElementsByTagName('time')[0].childNodes[0].nodeValue:"");																										
													newsContent = (newsNode.getElementsByTagName('contents').length>0?newsNode.getElementsByTagName('contents')[0].childNodes[0].nodeValue:"");
													
													lineBreakRegEx = new RegExp('\\[br\\]', "g");
												    newsContent = newsContent.replace(lineBreakRegEx, '<br/>');											
														
													new Insertion.Bottom("modules_content", '<span id="news_title"><h1>'+title+'</h1></span>');
													new Insertion.Bottom("modules_content", '<span id="news_datetime">'+time+'</span><br/><br/>');
													new Insertion.Bottom("modules_content", '<span id="news_text">'+newsContent+'</span><br/><br/>');
												}
												//$("modules_content").show();																	
												new Effect.Appear("modules_content", {duration:0.5});
										}.bind(this) 																  
							  });
		} else
		if (moduleName == "chat") {
			$("modules_content").update('<div id="modules_content_chat"></div>');
			$("modules_content").update('Nova verzija klepeta kmalu!<br/>New chat coming soon!<br/>');
			$("modules_content").update('<center><iframe src="/common/util/iframes/chat/chat.php?tvStation='+this.tvStationObj.getName()+'" height="165px" width="505px" style="border:none; border-width:0px;" scrolling="no"></iframe></center>');
		//	swfobject.embedSWF("/common/commenttv/commentTVJabber_final.swf", "modules_content_chat", "510", "160", "7.0.0", /*expressInstallLink=*/false, /*flashVars=*/ {serverAddress:"akademic.tv", roomName:"common", conferenceServer:"chat.akademic.tv"}, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true", wmode:"transparent"}, /*other object attribtues=*/{base:"http://www.wpntv.com",name:"WPNChat", id:"WPNChat"});					
		} else
		if (moduleName == "email") {
			$("modules_content").update('Posljite email informacijo o tem videu<br><br><form method="post" action="javascript:modules.sendEmail()"> Vase ime: <input name="Uname" id="Uname" size="26" type="text"> <br><br>Email posiljatelja: <input name="Uemail" id="Uemail" size="26" type="text"> <span id="Uemailverification" /> <br><br>Email naslovnika: <input name="Femail" id="Femail" size="26" type="text"> <span id="Femailverification" /> <br><br> <input value="Poslji" type="submit"> </form>');
			//TODO
		} else
		if (moduleName == "customLink") {
			window.open(this.tvStationObj.getCustomLinkUrl());
		} else
		if (moduleName == "downloadlink") {
			$("modules_content").update('<center><br/><br/><div id="downloadLinkHolder">Link to download this video will appear here if available.</div></center>');
			this.updateShowInfo();			
		}
	},
	showSubmitForm : function() {
		window.open( "/common/supportForm/supportForm.php?tvStation="+this.tvStationObj.getName(), "submitFormWindow", "status = 1, height = 360, width = 460, resizable = 0" );
	},
	showUploadForm : function() {
		//window.open( "/common/uploadForm/uploadForm.php?tvStation="+this.tvStationObj.getName(), "uploadFromWindow", "status = 1, height = 620, width = 460, resizable = 0" );
		window.open( "/common/upload/wpntv/?tvStation="+this.tvStationObj.getName(), "uploadFromWindow", "status = 1, height = 620, width = 460, resizable = 0" );
	},
	sendEmail : function() {
			/*var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (!filter.test($('Femail').getValue())) {	
				$("Femailverification").update("Vnesite pravilni E-mail naslov.");
				return;
			}
			if (!filter.test($('Uemail').getValue())) {							
				$("Uemailverification").update("Vnesite pravilni E-mail naslov.");									
				return;
			}*/
			emailParams = 'FEmail='+$('Femail').getValue()+'&UEmail='+$('Uemail').getValue()+'&UName='+$('Uname').getValue()+'&showid='+playlist.getCurrentlyPlayingShowID()+'&tvstation='+this.tvStationObj.getName();
			new Ajax.Request(this.emailScript, {
										method:'post',
										parameters : emailParams
							  });

		$("modules_content").update("Vase sporocilo je bilo oddano.");
	},
	parseDescription : function( descr ) {
		output = descr;
		linkPos = descr.lastIndexOf('[Download:');
		if (linkPos >= 0) {
			linkEnd = descr.indexOf(']',linkPos);
			extractedLink="";
			if (linkEnd > 0) {
				extractedLink = descr.substring(linkPos + 10, linkEnd);
				output = descr.substring(0,linkPos)+'<a targed="_blank" href="'+extractedLink+'">DOWNLOAD</a>'+descr.substring(linkEnd+1);				
			} 
		} 		
		return output;
	}
}

var tvStation;
var player;
var playlist;
var modules;
var localization;
var adsControl;

/*

STEP 1 : Load locale for webApp

*/
Event.observe(window, 'load', function() {
	if (!Object.isUndefined(TVStationSettings["locale"])) {
		localization = new Localization(TVStationSettings["locale"], function() { document.fire("wpntv:locale_loaded",{}) } ); //After locale is loaded we fire "wpntv:locale_loaded" event
	} else {
		localization = new Localization("default", function() { document.fire("wpntv:locale_loaded",{}) } ); // if no locale is specified we use the default one
	}
}.bind(this));


/*

STEP 2 : Initialize webApp and load necessary info depending on TVStationSettings 

*/
document.observe("wpntv:locale_loaded", function() {
	//INIT PAGE
	tvStation = new WPNTVStation( TVStationSettings );
	playlist = new Playlist(tvStation);
	player = new WPNPlayerComm(tvStation);
	adsControl = new AdsControl(tvStation);
	modules = new Modules(tvStation);

		this.playingFinished = player.playingFinished.bind(player); //playerBinds
		this.playerLoaded = player.playerLoaded.bind(player); //playerBinds
		this.onShowStartPlaying = player.playingStarted.bind(player);
		this.youtubePlayerStateChange = player.youtubePlayerStateChange.bind(player);
		
		//localize static content
		$("info_show_title").update(Locale["on-air"]);
		$("napis").update(Locale["webTV"]+" "+tvStation.getName()+".TV");
		
		$("uploadLinkText").update(Locale["sendUsVideo"]);
		$("userFeedbackText").update(Locale["feedback"]);
		
		//embed "scroll"
		
		swfobject.embedSWF("/common/channel_menu.swf", "channel_menu", "940", "60", "8.0.0", /*expressInstallLink=*/false, /*flashVars=*/ {stationName:tvStation.getName()}, /*flashParams=*/{allowScriptAccess:"always",quality:"high",allowFullScreen:"true",swLiveConnect:"true", seamlesstabbing:"true", wmode:"transparent"}, /*other object attribtues=*/{base:"http://www.wpntv.com",name:"WPNChannelMenu", id:"WPNChannelMenu"});
		//so = new SWFObject("common/channel_menu.swf", "stram", "940", "60", "7", "#ffffff");
		
	//GOOGLE ANALYTICS PART... try-catch just in case
	Try.these( function() { 
							if (tvStation.getUACCT() != "") {
								/*if (tvStation.getName() == "videodnevnik") {
									_udn="none";
									_ulink=1;						
								}
								_uacct = tvStation.getUACCT();
								urchinTracker();*/
								var pageTracker = _gat._getTracker(tvStation.getUACCT());
								pageTracker._trackPageview();
								//alert("local tracker"+tvStation.getUACCT());
							}
						}.bind(tvStation),
				function() { /* analytics fail */ } );

	Try.these( function() {
							/*_uacct = "UA-2486047-43";
							_udn="none"
							_ulink=1; 
							urchinTracker('global');*/
							//alert("global tracker "+_uacct);
							//GLOBAL TRACKER
							var pageTracker = _gat._getTracker("UA-2486047-43");
							pageTracker._setDomainName("none");
							pageTracker._setAllowLinker(true);
							pageTracker._trackPageview();
						},
				function() { /* analytics fail */ }
			  );

	var switchBar = new SwitchBar( tvStation.getSwitchbarIcons() );
	if (tvStation.getSwitchbarHasCustomColor()) {
		switchBar.setColor( tvStation.getSwitchbarCustomColor() );
	}
																																																																																																																																																																																																
	switchBar.renderFlashHome();			  
			  
}.bind(this) );
