/**
 * Video finder javascript
 *
 */

var VF_PAGING_LIMIT_LESS = 8;
var VF_PAGING_LIMIT_MORE = 16;

var debugDate = new Date();
debugDate = debugDate.getTime();
var previousLap;
function debugTime(str, hide) {
	var debugLap = new Date();
	debugLap = debugLap.getTime();
	var diff = debugLap - debugDate;

	if(!hide) {
		console.log(str+': '+diff+": "+(debugLap - previousLap));
	}
	previousLap = debugLap;
}

var DUMMYITEM = '<li class="vfItem"><a class="imgLink" title="undefined ---- undefined" href="undefined"></a><ul class="nettiItemDesc"><li class="timeStamp"><span class="time">undefined</span><span class="timeLeft">undefined</span></li><li class="name"><a href="undefined">undefined</a></li><li class="description"><p>undefined</p></li><li class="seriesMore">Näytä lisää: <a href="#" class="vfSeriesMore">undefined</a></li></ul></li></li>';

function videoFinder() {
console.log('creating finder');
	this.searchDefaultText = 'Kirjoita etsimäsi ohjelman nimi tähän';

	this.container = '#videoFinder';
	this.currentMode = 'thumbnails';
	this.sections = new Array('video_episode', 'video', 'audio', 'series_list');
	this.sectionsLang = new Array('Jaksot', 'Klipit', 'Podcastit', 'Sarjat');
	this.sectionsType = new Array('thumbnails', 'thumbnails', 'thumbnails', 'series_list');
	this.selectedTab = 0;
	this.selectedSorting = 'latestdesc';
	this.selectedSection = 0;
	this.seriesList = new Array(); // This array contains the series names suggested to the user.
	this.sortings = new Array('latestdesc', 'most_watched', 'most_commented');
	this.sortingsLang = new Array('Uusimmat', 'Katsotuimmat', 'Kommentoiduimmat');
	this.tabs = new Array();
	this.tabIds = new Array();
	this.targetPage = '';
	this.targetPageNode = '';
	this.finderId = 'videoFinder'; // IMPROVE allow multiple instances		
	this.forcedSeriesFilter = '';
	this.forcedSeriesGroupFilter = '';
	this.backgroundPosition = '';
	this.geoBlockFilter = '__';
	
	if(vf_url_series_filter) {
		this.seriesFilter = urlencode(vf_url_series_filter);
	}
	else {
		this.seriesFilter = '__';
	}
	
	if(vf_url_series_group_filter) {
		this.seriesGroupFilter = urlencode(vf_url_series_group_filter);		
	}
	else {
		this.seriesGroupFilter = '__';
	}
	
	this.currentTab = false;

	var thisFinder = this;

	this.initialize = function(){
		// Set the link target for the video links
		var href = '';
		//optional page target
		if( vf_target_page && vf_target_node_nid ){
			//link to another page
			href = base_url+'/'+vf_target_page;
			this.targetPageNode = vf_target_node_nid;
		}
		else {
			//links stay on this page
			href = location.href;
			if(  href.indexOf('?') != -1){
				href = href.split('?');
				href = href[0];
			}
		}
		this.targetPage = href;

		$(this.container).empty();

		this.createTabContainer();
		this.createSearchContainer();
		this.createSubCategoryContainer();
		this.createSortContainer();
		this.createAdSlot();
		
	}
	
	
	this.createTabContainer = function(){
		var html = ''
		html += '<div class="contentTabs"><ul class="vfTabs vfTabsLeft nettiTabNav"></ul><ul class="vfTabs vfTabsRight"></ul></div>'+"\n\n";
	
		$(this.container).append(html);
	}
	
	
	this.createAdSlot = function(){
		if (Drupal.settings.mu_media_finder && Drupal.settings.mu_media_finder.adHtml) {
			var html = Drupal.settings.mu_media_finder.adHtml;
		
			$(this.container).append(html);
		}
	}
	
	this.createSearchContainer = function(){
		var html = ''
		html += '		<div class="vfSearchHolder clearFix vfControls">\
			<div class="searchBoxStyle">\
				<fieldset>\
					<input type="text" class="vfSearchInput" value="'+this.searchDefaultText+'" />\
					<button class="vfSearchButton">Search</button>\
				</fieldset>\
			</div>\
			\
			<div class="vfSearchSeriesSuggestions">\
				<ul class="vfSearchSeriesSuggestionsList">\
				</ul>\
			</div>\
		</div>\
		\
		<div class="vfSeriesFilter vfControls">Näytetään ohjelman "<span class="vfSeriesFilterCurrent">';
		
		// In case the series filter was set from the URL
		if(this.seriesFilter != '__') {
			html += this.seriesFilter;
		}
		else {
			html += "";
		}
		
		html += '</span>" jaksot | <a href="#" class="vfSeriesFilterClear">Tyhjennä valinta</a></div>\
		'+"\n\n";
	
		$(this.container).append(html);
		
		// In case the series filter was set from the URL
		if(this.seriesFilter != '__') {
			$('#'+this.finderId+' .vfSeriesFilter').show();
		}
		
		this.bindSearchEvents();
	}
	
	this.createSubCategoryContainer = function() {
		var html = '';
		html += '<div class="vfSubCategories vfControls"></div>';
		$(this.container).append(html);
	}

	
	this.createSortContainer = function(){
		thisFinder = this;
		
		var html = ''
		html += '<div class="vfSorting vfControls">\
		<ul class="vfMode"><li class="vfSelectMode thumbnails';
		if(thisFinder.currentMode == 'thumbnails') {
			html += ' selected'
		}
		html += '"><a href="#">Kaikki sis&auml;lt&ouml;</a></li>\
		<li class="vfSelectMode series_list';
		if(thisFinder.currentMode == 'series_list') {
			html += ' selected'
		}
		html += '"><a href="#">Listaa sarjat</a></li></ul>\
		<ul class="vfSortings"></ul>\
		<ul class="vfGeoBlock"><li><a href="#" title="N&auml;yt&auml; vain kaikkialla maailmassa katsottavissa oleva media"></a></li></ul></div>';
		
		$(this.container).append(html);
		
		var aLength = this.sortings.length;
		
		var ii = 0;
		
		for(i=0;i<aLength;i++){
			html = '<li class="'+this.sortings[i];
			if(this.sortings[i] == this.selectedSorting) {
				html += ' selected';
			}
			html +='"><a href="#" id="vfSort-' + this.sortings[i] + '">' + this.sortingsLang[i] + '</a></li>';
			
			$('.vfSorting ul.vfSortings').append(html);
			
			$('#vfSort-' + this.sortings[i]).click(function(){
				var sorting = $(this).attr('id').split("-")[1];
				thisFinder.setSortOrder(sorting);
				
				return false;
			});
			
			ii++;
		}
		
		$('.vfMode li.thumbnails').click(function(){
			thisFinder.setMode('thumbnails');
			thisFinder.currentTab.loadAllSections();
			return false;
		});
		
		$('.vfMode li.series_list').click(function(){
			thisFinder.setMode('series_list');
			thisFinder.seriesFilter = '__';
			thisFinder.seriesGroupFilter = '__';
			return false;
		});
		
		
		$('.vfGeoBlock a').click(function(){
			if( $(this).hasClass('geoFreeContent') ){
				//remove geo free filter
				$(this).removeClass('geoFreeContent');
				thisFinder.geoBlockFilter = '__';
				var title = 'Näytä vain kaikkialla maailmassa katsottavissa oleva media';
				$(this).attr('title', title);				
			}
			else{
				//add geo free filter
				$(this).addClass('geoFreeContent');
				thisFinder.geoBlockFilter = '0';
				var title = 'Näytä kaikki media';
				$(this).attr('title', title);
			}
			thisFinder.currentTab.loadAllSections();
			return false;
		});
	}
	
	


	/**
	 * videoFinder.addTab()
	 *
	 */
	 
	this.addTab = function(channelId, channelName, channelNameGenitive, channelUrl, channelLabel, channelLogo, type, extraBackground){
		thisFinder = this;

		this.tabIds.push(channelId);
		this.tabs[channelId] = new videoFinderTab(thisFinder, channelId, channelName, channelNameGenitive, channelUrl, channelLabel, channelLogo, thisFinder.container, thisFinder.sections, thisFinder.sectionsLang, thisFinder.sectionsType, type, extraBackground);

		$('#' + this.tabs[channelId].container + 'Tab').click(function(){
			thisFinder.switchTab(thisFinder.tabs[channelId]);
			thisFinder.currentTab.loadAllSections();
			thisFinder.updateCookie();
			
			return false;
		});

	}


	/**
	 * videoFinder.switchTab()
	 *
	 */
	 
	this.switchTab = function(tab){
		console.log('Switching tab');
		// Highlight selected tab
		$('#'+thisFinder.finderId+' .vfTab a').removeClass('activeTabNav');
		$('#vfChannel'+tab.id+'Tab a').addClass('activeTabNav');
		
		if(!tab.sectionsInitialized) {
			tab.initSections();
		}

		//switching banner ads, css and player ad
		//issue #0005832
		//if we have custom banner for an extra tab
		//insert ad source into the iframe, change iframe height and width
		//show it=> hide the #topBannerHolder
		//the iframe id is #iframeExtraTabCustomBannerAds
		//all the variable to check are added on the media finder template
		//see the template to find out the name of the variables
		//start checking if this is extra tab
		if (tab.extraNid!=false){
			var extraTabHasBannerAd = eval("extraTabHasBanner_"+tab.extraNid);
			
			if (typeof extraTabHasBannerAd !== 'undefined' && extraTabHasBannerAd!=0){
				//console.log('showing extra tab banner');
				var extraTabBannerHeight =  eval("extraTabBannerHeight_"+tab.extraNid);
				//console.log("extra tab banner height: "+extraTabBannerHeight);
				var extraTabBannerWidth =  eval("extraTabBannerWidth_"+tab.extraNid);
				//console.log("extra tab banner width: "+extraTabBannerWidth);
				var extraTabBannerSource =  eval("extraTabBannerSource_"+tab.extraNid);
				//console.log("extra tab banner source: "+extraTabBannerSource);
				
				//we are having a top banner to replace the current one
				//prepare the iframe before showing it
				$('#iframeExtraTabCustomBannerAds').attr('src',extraTabBannerSource);
				$('#iframeExtraTabCustomBannerAds').attr('height',extraTabBannerHeight);
				$('#iframeExtraTabCustomBannerAds').attr('width',extraTabBannerWidth);
				$('#topBannerHolder').hide();
				$('.topBannerHolder').show();				
			}
			
			//custom css
			var extraTabCustomCss = eval("extraTabCustomCss_"+tab.extraNid);
			if (typeof extraTabCustomCss !== 'undefined'){
				//console.log('switching custom css to '+extraTabCustomCss);
				//switching many extra tab may cause side effect
				//remove custom css first just in case
				$('#extraTabCSS').remove();
				var linkElement = '<link type="text/css" id="extraTabCSS" rel="stylesheet" media="all" href="'+extraTabCustomCss+'" />';
				$('head').append(linkElement);
			}
			
			//custom player ads
			//we might not have player sometime so we must check if the div exists
			//the id of the div is #ruutuAdSpaceMainAd
			//if exists, we inject an iframe right below it
			//set source, width, height then show hide
			if ($("#ruutuAdSpaceMainAd").length > 0){
				//we have ruutu main ads
				//insert new div with frame right after #ruutuAdSpaceMainAd
				//but first, check if it's already there
				//console.log("custom player ad div: "+$("#extraTabCustomPlayerAdDiv").length);
				if ($("#extraTabCustomPlayerAdDiv").length <= 0){
					$("<div id = \"extraTabCustomPlayerAdDiv\" class=\"ruutuAdSpace\" style=\"display:none;\"><iframe id='iframeExtraTabCustomPlayerAds' frameborder=\"0\" height=\"0\"></iframe></div> ").insertAfter('#ruutuAdSpaceMainAd');
				}
				
				//start checking if this extra tab having custom player ad
				var extraTabHasCustomPlayerAd = eval("extraTabHasCustomPlayerAd_"+tab.extraNid);
				if (typeof extraTabHasCustomPlayerAd !== 'undefined' && extraTabHasCustomPlayerAd!=0){
					//console.log('switching custom player ad');
					var extraTabCustomPlayerAdHeight =  eval("extraTabCustomPlayerAdHeight_"+tab.extraNid);
					//console.log("extra player ad height: "+extraTabCustomPlayerAdHeight);
					var extraTabCustomPlayerAdWidth =  eval("extraTabCustomPlayerAdWidth_"+tab.extraNid);
					//console.log("extra player ad width: "+extraTabCustomPlayerAdWidth);
					var extraTabCustomPlayerAdSource =  eval("extraTabCustomPlayerAdSource_"+tab.extraNid);
					//console.log("extra tab player ad source: "+extraTabCustomPlayerAdSource);
					
					//now we show and hide divs
					//prepare the iframe before showing it
					$('#iframeExtraTabCustomPlayerAds').attr('src',extraTabCustomPlayerAdSource);
					$('#iframeExtraTabCustomPlayerAds').attr('height',extraTabCustomPlayerAdHeight);
					$('#iframeExtraTabCustomPlayerAds').attr('width',extraTabCustomPlayerAdWidth);
					$('#ruutuAdSpaceMainAd').hide();
					$('#extraTabCustomPlayerAdDiv').show();					

				}
			}
			
		}
		else{
			//console.log('showing normal banner and normal css');
			//if no custom ads, must be normal tabs or the extra tab has no custom ads
			
			//reset custom banner iframe
			$('#iframeExtraTabCustomBannerAds').attr('src','');
			$('#iframeExtraTabCustomBannerAds').attr('height',0);
			$('#iframeExtraTabCustomBannerAds').attr('width',0);
			
			//remove css
			$('#extraTabCSS').remove();
			
			$('#topBannerHolder').show();
			$('.topBannerHolder').hide();
			
			//remove extra tab custom player ads if exists
			if ($("#ruutuAdSpaceMainAd").length > 0){
				//reset custom player ad iframe
				$('#iframeExtraTabCustomPlayerAds').attr('src','');
				$('#iframeExtraTabCustomPlayerAds').attr('height',0);
				$('#iframeExtraTabCustomPlayerAds').attr('width',0);
				$('#extraTabCustomPlayerAdDiv').hide();
			}
			
			//just to make sure we have the player ads
			//if yes, show it
			if ($("#ruutuAdSpaceMainAd").length > 0){
				$('#ruutuAdSpaceMainAd').show();
			}
		}
		
				
		$(this.container + " .vfSection").hide();
		this.selectedTab = tab.id;
	
		// Show sections on this tab
		$('#vfChannel' + tab.id + 'Sections').show();
		$('#vfChannel' + tab.id + 'Sections .vfSection.'+thisFinder.currentMode).show();
		$('#vfChannel' + tab.id + 'Sections .vfSection.logo').show();
		
		thisFinder.currentTab = tab;
		
		if( thisFinder.currentTab.channelBanner === false){
			$('.vfAdContainer').show();
		}
		else{
			$('.vfAdContainer').hide();
		}
		
		//Custom background
		if( typeof thisFinder.currentTab.extraBackground !== 'undefined' ){
			$('body').attr('style', '');
			$('body').css('background-image', 'url("'+thisFinder.currentTab.extraBackground+'")');
		}
		else{
			$('body').attr('style', '');
			if($.browser.msie) {
				var pos = videoFinder.backgroundPosition.split(',');
				$('body').css('background-position-x', '50%');
				$('body').css('background-position-y', pos[1]);
			}
			else{
				$('body').css('background-position', thisFinder.backgroundPosition);
			}
		}
		
		// Only allow series filtering on the "All videos" tab, to avoid empty pages and confusion
		// unless we are forcing a channel filter in which case we dont load the all tab for series
		// filtering
		if(!vf_show_tab_channel_id && tab.channel != 'all') {
			thisFinder.clearSeriesFilter(thisFinder);
		}
		// Empty the search box when clearing the series filter, unless were going to search results
		if(tab.channel != 'all' && tab.channel != 'SearchResults') {
			$('#'+thisFinder.finderId+' .vfSearchInput').val(thisFinder.searchDefaultText);
		}
		
		// Don't show mode toggle or sorters on search results page 
		if(tab.channel == 'SearchResults') {
			$('#'+thisFinder.finderId+' .vfSorting').hide();
		}
		else {
			$('#'+thisFinder.finderId+' .vfSorting').show();		
		}
		
		//Update the sort channel string 
		if(tab.channel == 'all') {
			$('.vfSelectMode.thumbnails a').html('Kaikki sis&auml;lt&ouml;');
		}
		else{
			$('.vfSelectMode.thumbnails a').html(tab.nameGenitive+' sis&auml;lt&ouml;');
		}
		
		//tab.loadAllSections(this);
	}


	this.setSortOrder = function(sorting){
		var thisViewer = this;
		var aLength = this.tabIds.length;
	
		for(i=0;i<aLength;i++){
			var tabId = this.tabIds[i];
			thisViewer.tabs[tabId].sort_by = sorting;
		}
		
		thisViewer.selectedSorting = sorting;
		thisViewer.updateCookie();
		
		$('.vfSortings li').removeClass('selected');
		$('.vfSortings li.'+sorting).addClass('selected');

		this.tabs[this.selectedTab].loadAllSections(this);
	}


	/**
	 * videoFinder.setMode()
	 *
	 */
	 
	this.setMode = function(mode) {
	console.log('Setting mode');
		this.currentMode = mode;
		$('.vfMode li').removeClass('selected');
		$('.vfMode li.'+mode).addClass("selected");
		
		
		var tabSelector = thisFinder.currentTab.container+'Sections';
		console.log(tabSelector);
		
 		// Sections with class "hideMe" don't have any content to show
		if(mode == 'thumbnails') {
			$('#'+thisFinder.finderId+' #'+tabSelector+' .vfSection.thumbnails:not(.hideMe)').show();
			$('#'+thisFinder.finderId+' #'+tabSelector+' .vfSortings').show();
			$('#'+thisFinder.finderId+' #'+tabSelector+' .vfSection.series_list').hide();
		}
		else if(mode == 'series_list') {
			$('.vfSeriesFilter').hide();
			$('.vfSubCategories').hide();
		
			$('#'+thisFinder.finderId+' #'+tabSelector+' .vfSection.thumbnails').hide();
			$('#'+thisFinder.finderId+' #'+tabSelector+' .vfSortings').hide();
			$('#'+thisFinder.finderId+' #'+tabSelector+' .vfSection.series_list').show();
		}
		
		// This is needed to prevent showing other channel's videos if channel was 
		// switched during series_list mode.
		// TODO only load when necessary, i.e. when tab hasn't changed.
		//this.currentTab.loadAllSections();
	}
	
	/**
	 * videoFinder.updateCookie()
	 *
	 */

	this.updateCookie = function(cookieArray){
		thisFinder = this;
		console.log('updateCookie');
		
		//If on search results tab we need to set channel tab to 'all'
		if( thisFinder.currentTab.id == 'SearchResults'){
			thisFinder.currentTab.id = 'all';
		}
		
		var sectionsJSON = this.sectionsJSON(thisFinder);
		$.cookie('vFinder-'+currentNid, thisFinder.currentTab.id+'#'+thisFinder.selectedSorting+'#'+thisFinder.seriesFilter+'#'+thisFinder.seriesGroupFilter+'#'+sectionsJSON, { expires: 0, path: "/" });
		
		if( this.targetPageNode != '' ){
			$.cookie('vFinder-'+this.targetPageNode, thisFinder.currentTab.id+'#'+thisFinder.selectedSorting+'#'+thisFinder.seriesFilter+'#'+thisFinder.seriesGroupFilter+'#'+sectionsJSON, { expires: 0, path: "/" });
		}
	}
	
	/**
	 * videoFinder.handleCookie()
	 *
	 */
	
	this.handleCookie = function(){
		thisFinder = this;
		
		//If we are on the frontpage of ruutu clear any cookie
		if( window.location.href == base_url+'/'){
			$.cookie('vFinder-'+currentNid, null);
			$.cookie('vFinder-'+this.targetPageNode, null);
		}
		//try to find cookie for current finder
		if( $.cookie('vFinder-'+currentNid) ){
			//Break apart to use			
			cookieParts = $.cookie('vFinder-'+currentNid).split('#');
			
			//Tab
			if(vf_show_tab_channel_id !== false){
				//If url channel tab is set, override cookie
				var match = false;
				//Failsafe
				for( i in videoFinder.tabs ){
					if (vf_show_tab_channel_id == videoFinder.tabs[i].id ){
						var match = true;
					}
				}
				if( match ){
					thisFinder.switchTab(videoFinder.tabs[vf_show_tab_channel_id]);
				}
				else{
					thisFinder.switchTab(videoFinder.tabs[cookieParts[0]]);
				}	
			}
			else{
				thisFinder.switchTab(videoFinder.tabs[cookieParts[0]]);
			}
			
			//Sort
			thisFinder.tabs[cookieParts[0]].sort_by = [cookieParts[1]];
			$('.vfSortings li').removeClass('selected');
			$('.vfSortings li.'+cookieParts[1]).addClass('selected');
			thisFinder.selectedSort = cookieParts[1];
			
			if( !vf_url_series_filter || !vf_url_series_group_filter){
				//Series Filter
				if( cookieParts[2] != '__' && cookieParts[3] == '__' ){
					//Just series filter
					thisFinder.seriesFilter = cookieParts[2];
					
					$('.vfSeriesFilterCurrent').html(urldecode(cookieParts[2]));
					$('.vfSeriesFilter').show();
				}
				
				//Series Group Filter
				if( cookieParts[3] != '__' ){
					thisFinder.seriesGroupFilter = cookieParts[3];
					$('.vfSeriesFilterCurrent').html(urldecode(cookieParts[3]));
					$('.vfSeriesFilter').show();
					
					//in this case cookieParts[2] would be the sub series of the group
					if( cookieParts[2] != '__' ){
						thisFinder.seriesFilter = cookieParts[2];
					}
				}
			}
			
			//Section Paging
			var sections = eval('('+cookieParts[4]+')');
			
			for(z=0; z < sections.length; z++){
				thisFinder.currentTab.sectionObjects[z].mode = sections[z]['mode'];
				thisFinder.currentTab.sectionObjects[z].pagingCurrentPage = sections[z]['pagingCurrentPage'];
				thisFinder.currentTab.sectionObjects[z].pagingLimit = sections[z]['pagingLimit'];
				thisFinder.currentTab.sectionObjects[z].pagingOffset = sections[z]['pagingOffset'];
			}
				
		}
		else{
			if(vf_show_tab_channel_id !== false){
				//If url channel tab is set go to that
				thisFinder.switchTab(videoFinder.tabs[vf_show_tab_channel_id]);	
			}
			else{
				thisFinder.switchTab(videoFinder.tabs['all']);
			}
			
			thisFinder.updateCookie();
		}	
	}


	/**
	 * videoFinder.bindSearchEvents()
	 * Makes the series filter search box work.
	 *
	 */
	 
	this.bindSearchEvents = function() {
		var thisFinder = this;
		
		// Clear the field on click
		$('#'+thisFinder.finderId+' .vfSearchInput').click( function(){
			if( $(this).val() == thisFinder.searchDefaultText){
				$(this).val('');
			}
		});
		
		// Get the series suggestions list for the search box.
		if(vf_show_tab_channel_id){
			var seriesListId = vf_show_tab_channel_id; 
		}
		else{
			var seriesListId = 'all';
		}
		
		$.get(base_url+"/ajax/media_get_netti_tv_series_list/"+seriesListId, function(data) {
		 	data = eval("("+data+")");
		 	
		 	// Pregenerate lowercase names for matching in the series suggester
		 	for(var i = 0;i<data.length;i++) {
		 		data[i]['name_lowercase'] = data[i]['name'].toLowerCase();
		 	}
		 	
		 	thisFinder.seriesList = data;
		});
		
		// Handle typing into the search box
		$('#'+thisFinder.finderId+' .vfSearchInput').bind("keyup", function(e) {		
		//debugTime(e.keyCode);
			if(e.keyCode == 13 && $('#'+thisFinder.finderId+' .vfSearchInput').val().length > 0) {
				// Enter was pressed, do a search
				var searchTerm = $(this).parent().find('.vfSearchInput').val();
				thisFinder.search(searchTerm);
				$("html").unbind("click");
				return false;
			}
			else {
				// Otherwise, suggest series
				$('#'+thisFinder.finderId+' .vfSearchSeriesSuggestions').show();
	
				// Populate the list
				var results = '<li class="title">Sarjat</li>';
				var progAr = thisFinder.seriesList;
				//debugTime('before loop');
				
				var lookingFor = $('#'+thisFinder.finderId+' .vfSearchInput').val().toLowerCase();
				
				for(i=0; i<progAr.length; i++){

					var progName = progAr[i]['name_lowercase'].match(lookingFor);

					if (progName != null ){
						if(progAr[i]['is_group'] == 1){
							group = 'group';
						}
						else {
							group = '';
						}
						
						if( progAr[i]['override'] == null ){
							results += '<li><a href="#" class="'+group+'" id="'+progAr[i]['url_encode_name']+'">'+progAr[i]['name']+'</a></li>';
						}
						else{
							results += '<li title="'+progAr[i]['name']+' ---- Tämän sarjan jaksoja ei ole nähtävillä verkossa, sillä sarjalle ei ole verkkoesitysoikeuksia" class="overrideSeries">'+progAr[i]['name']+'</li>';
						}
					}
				}
				//debugTime('after loop');
				$('.vfSearchSeriesSuggestionsList').html(results);

				// Set styles
				$('.vfSearchSeriesSuggestionsList li').hover(
					function () {
						$(this).css('background-color', '#E5E6E6');
					},
					function () {
						$(this).css('background-color', 'transparent');
					}
				);

				
				// Close the suggestions when clicking outside
				$('html').click( function(e) {
					if( !($(e.target).is('#'+thisFinder.finderId+' .vfSearchSeriesSuggestions') || $(e.target).is('#'+thisFinder.finderId+' .vfSearchInput')) ){
						$("html").unbind("click");
						$('#'+thisFinder.finderId+' .vfSearchSeriesSuggestions').hide();
						$('#'+thisFinder.finderId+' .vfSearchInput').val(thisFinder.searchDefaultText);	
					}
					return false;
				});
				
				
				// Set filter when clicking on the series links
				$('.vfSearchSeriesSuggestionsList li a').click( function() {
					$("html").unbind("click");
					thisFinder.setSeriesFilter(thisFinder, $(this));
					
					return false;
				});
			
			}
		
		}); // end function "bind keyup"
		
		
		// Clearing the series filter
		$('#'+thisFinder.finderId+' .vfSeriesFilterClear').click( function(){
			thisFinder.clearSeriesFilter(thisFinder);
			$('#'+thisFinder.finderId+' .vfSearchInput').val(thisFinder.searchDefaultText);
			thisFinder.currentTab.loadAllSections();
			return false;
		});
		
		
		$('#'+thisFinder.finderId+' .vfSearchButton').click(function() {
			var searchTerm = $(this).parent().find('.vfSearchInput').val();
			thisFinder.search(searchTerm);
			return false;
		});
	}

	
	/**
	 * videoFinder.setSeriesFilter()
	 *
	 * @param finder Object The Video finder we're setting the filter on
	 * @param anchor jQuery object The anchor that was clicked
	 *
	 */
	 
	this.setSeriesFilter = function(finder, anchor) {
		// Show the series filter status on this Finder
		// IMPROVE allow multiple instances
		var vfSeriesFilter = anchor.parent().parent().parent().parent().parent();

		vfSeriesFilter.find('.vfSeriesFilterCurrent').html(anchor.html());
		vfSeriesFilter.find('.vfSeriesFilter').show();
	
		if(anchor.hasClass('group')){
			finder.seriesGroupFilter = anchor.attr('id');
			finder.seriesFilter = '__';
		}
		else {
			finder.seriesFilter = anchor.attr('id');
			finder.seriesGroupFilter = '__';
		}
		
		// Reset paging
		for( i in finder.tabs['all'].sectionObjects ){
			finder.tabs['all'].sectionObjects[i].pagingLimit = 8;
			finder.tabs['all'].sectionObjects[i].pagingOffset = 0;
			finder.tabs['all'].sectionObjects[i].mode = 'less';
		} 
		
		finder.setMode('thumbnails');
		
		// We always show series from all channels, so to avoid confusion, let's
		// switch to the all series tab, unless we are forcing a channel filter:
		if( vf_show_tab_channel_id ){
			finder.switchTab(thisFinder.tabs[vf_show_tab_channel_id]);
			finder.tabs[vf_show_tab_channel_id].loadAllSections();
		}
		else{
			finder.switchTab(thisFinder.tabs['all']);
			finder.tabs['all'].loadAllSections();
		}
		
		
		finder.updateCookie();
		
		$('#'+finder.finderId+' .vfSearchInput').val(finder.searchDefaultText);
		$('#'+finder.finderId+' .vfSearchSeriesSuggestions').hide();
	}
	
	/**
	 * videoFinder.setSubCategories()
	 *
	 * @param group Object The program group information
	 *
	 */
	
	this.setSubCategories = function (group) {
		var thisFinder = this;
		
		var selected = '';
		var html = '<ul><li>Alakategoriat:&nbsp;</li> ';
		for( i=0; i<group['sub_serieses'].length; i++ ){
			if( group['sub_serieses'][i]['sub_series_name'] == thisFinder.seriesFilter ){
				selected = ' class="selected"';
			}	
			else {
				selected = '';
			}
			if( i == group['sub_serieses'].length-1 ){ 
				html += '<li'+selected+'><a id="'+group['sub_serieses'][i]['ulr_encoded_sub_series_name']+'">'+group['sub_serieses'][i]['sub_series_name']+'</a></li>';
			}
			else{
				html += '<li'+selected+'><a id="'+group['sub_serieses'][i]['ulr_encoded_sub_series_name']+'">'+group['sub_serieses'][i]['sub_series_name']+'</a>  |</li> ';
			}
		}
		html += '</ul>';
		
		$('.vfSubCategories').html('');
		$('.vfSubCategories').html(html);
		$('.vfSubCategories').show();
		
		$('.vfSubCategories a').click( function(){
			thisFinder.selectSubCategory(thisFinder, $(this));
			return false;
		});
	}
	
	/**
	 * videoFinder.selectSubCategory()
	 *
	 * @param finder Object The Video finder we're setting the filter on
	 * @param anchor jQuery object The anchor that was clicked
	 *
	 */
	
	this.selectSubCategory = function (finder, anchor){
		
		finder.seriesFilter = anchor.html();
		
		// Reset paging
		finder.tabs['all'].pagingLimit = 8;
		finder.tabs['all'].pagingOffset = 0;
		
		finder.setMode('thumbnails');
		
		// We always show series from all channels, so to avoid confusion, let's
		// switch to the all series tab:
		finder.switchTab(thisFinder.tabs['all']);
		
		finder.tabs['all'].loadAllSections();
		
		finder.updateCookie();
		
	}

	
	/**
	 * videoFinder.clearSeriesFilter()
	 * @param finder Object The Video finder we're clearing the filter on
	 * @param anchor Jquery object the link that was clicked
	 *
	 */
	 
	this.clearSeriesFilter = function(finder) {
		// Clear the series filter and series group filter from thisFinder
		finder.seriesFilter = '__';
		finder.seriesGroupFilter = '__';
		
		$('#'+finder.finderId+' .vfSeriesFilter').hide();
		$('#'+finder.finderId+' .vfSubCategories').hide();
		
		finder.updateCookie();

		// Can't set search default text here, since we want to keep it in the box after an actual search.
	}
	
	
	/**
	 * videoFinder.search
	 *
	 */
	
	this.search = function(searchTerm) {
		// Hide suggestions
		$('#'+this.finderId+' .vfSearchSeriesSuggestions').hide();
		
		// Generate search JSON array
		if( searchAllSites == '1' ){
			var params = {'search':searchTerm, 'groups': {'video': {'types':['video_clip']}, 'video_episode': {'types': ['video_episode']}, 'audio': {'types':['audio']}}};
		}
		else{
			var params = {'search':searchTerm, 'groups': {'video': {'types':['video_clip'], 'site':[searchSite]}, 'video_episode': {'types': ['video_episode'], 'site':[searchSite]}, 'audio': {'types':['audio'], 'site':[searchSite]}}};
			//var params = {"search":searchTerm, "groups":[{"types":["video_episode","video_clip","audio"],"site":[searchSite]}]}
		}
		
		params = $.toJSON(params); // use jquery.json plugin
		
		$.post(searchUrl, { params: params },
			function(data){

				var results = eval('(' + data + ')');

				if(isEmpty(results)) {
					cResults = [{"id":"0","nid":"0","modified":"","title":"Ei hakutuloksia","teaser":"","nodeurl":"","thumbnailuri":""}];
					eResults = [{"id":"0","nid":"0","modified":"","title":"Ei hakutuloksia","teaser":"","nodeurl":"","thumbnailuri":""}];
					aResults = [{"id":"0","nid":"0","modified":"","title":"Ei hakutuloksia","teaser":"","nodeurl":"","thumbnailuri":""}];
				}
				else {
					if(isEmpty(results['video'])) {
						cResults = [{"id":"0","nid":"0","modified":"","title":"Ei hakutuloksia","teaser":"","nodeurl":"","thumbnailuri":""}];
					}
					else{
						cResults = results['video'];
					}
					
					if(isEmpty(results['video_episode'])) {
						eResults = [{"id":"0","nid":"0","modified":"","title":"Ei hakutuloksia","teaser":"","nodeurl":"","thumbnailuri":""}];
					}
					else {
						eResults = results['video_episode'];
					}
					
					if(isEmpty(results['audio'])) {
						aResults = [{"id":"0","nid":"0","modified":"","title":"Ei hakutuloksia","teaser":"","nodeurl":"","thumbnailuri":""}];
					}
					else {
						aResults = results['audio'];
					}
				}
				
				thisFinder.removeTab('SearchResults');
				thisFinder.addTab('SearchResults', 'Hakutulokset', '','','','', 'searchResults');
				
				var searchTab = thisFinder.tabs['SearchResults'];
				
				thisFinder.switchTab(thisFinder.tabs['SearchResults']);

				var cIndex = -1;
				var eIndex = -1;
				var aIndex = -1;
				for(var i = 0;i < searchTab.sections.length; i++) {
					if(searchTab.sections[i] == 'video') {
						cIndex = i;
					}
					if(searchTab.sections[i] == 'video_episode') {
						eIndex = i;
					}
					if(searchTab.sections[i] == 'audio') {
						aIndex = i;
					}
				}

				var videoSection = searchTab.sectionObjects[cIndex];
				var videoEpisodeSection = searchTab.sectionObjects[eIndex];
				var audioSection = searchTab.sectionObjects[aIndex];
				
				var cHtml = '';
				var eHtml = '';
				var aHtml = '';
				
				for(var i = 0; i< cResults.length; i++) {
					cHtml += videoSection.createListElement(false, cResults[i]);
				}
				
				for(var i = 0; i< eResults.length; i++) {
					eHtml += videoEpisodeSection.createListElement(false, eResults[i]);
				}
				
				for(var i = 0; i< aResults.length; i++) {
					aHtml += audioSection.createListElement(false, aResults[i]);
				}

				var videoResultContainerId = '#'+videoSection.sectionId + ' ul.payload';
				var videoEpisodeResultContainerId = '#'+videoEpisodeSection.sectionId + ' ul.payload';
				var audioResultContainerId = '#'+audioSection.sectionId + ' ul.payload';
				
				$(videoResultContainerId).append(cHtml);
				$(videoEpisodeResultContainerId).append(eHtml);
				$(audioResultContainerId).append(aHtml);

				$('#'+videoSection.sectionId+' .vfLoader').hide();
				$('#'+videoEpisodeSection.sectionId+' .vfLoader').hide();
				$('#'+audioSection.sectionId+' .vfLoader').hide();
			}
		);
	}
	
	
	/**
	 * videoFinder.removeTab
	 *
	 */
	 
	this.removeTab = function(channel) {
		//thisFinder.tabs[channel] = false;
		// Remove the tab control
		$('#vfChannel'+channel+'Tab').remove();
		// Remove sections
		$('#vfChannel'+channel+'Sections').remove();
	}
	
	this.sectionsJSON = function(){
		var thisFinder = this;
		var sectionsJSON = '[';
	
		if( typeof thisFinder.tabs[thisFinder.currentTab.channel] != 'undefined' ){
			//var sectionsJSON += '{"tabid":"'+thisFinder.currentTab.channel+'", "section": [';
			for( z=0; z<thisFinder.tabs[thisFinder.currentTab.channel].sectionObjects.length; z++){
				sectionsJSON += '{ "sectionid":"'+thisFinder.tabs[thisFinder.currentTab.channel].sectionObjects[z].sectionId+'",';
				sectionsJSON += '"mode":"'+thisFinder.tabs[thisFinder.currentTab.channel].sectionObjects[z].mode+'",';
				sectionsJSON += '"pagingCurrentPage":"'+thisFinder.tabs[thisFinder.currentTab.channel].sectionObjects[z].pagingCurrentPage+'",';	
				sectionsJSON += '"pagingLimit":"'+thisFinder.tabs[thisFinder.currentTab.channel].sectionObjects[z].pagingLimit+'",';	
				sectionsJSON += '"pagingOffset":"'+thisFinder.tabs[thisFinder.currentTab.channel].sectionObjects[z].pagingOffset+'"';					 
				if( z == thisFinder.tabs[thisFinder.currentTab.channel].sectionObjects.length-1 ){
					sectionsJSON += '}';	
				}
				else{
					sectionsJSON += '},';
				}
			}
			sectionsJSON += ']';
		}
		
		return sectionsJSON;
	}
	
	this.initialize();

} // end function videoFinder


/**
 * Object videoFinderTab
 *
 */
function videoFinderTab(parentFinder, channelId, channelName, channelNameGenitive, channelUrl, channelLabel, channelLogo, container, sections, sectionsLang, sectionsType, type, extraBackground) { 

	this.id = channelId;
	this.name = channelName;
	this.nameGenitive = channelNameGenitive;
	
	this.channelUrl = channelUrl;
	this.channelLabel = channelLabel;
	this.channelLogo = channelLogo;
	this.channelBanner = true;
	
	if( channelLogo == '' ){
		this.channelBanner = false;
	}
	
	this.extraBackground = extraBackground;
	
	this.container = 'vfChannel' + channelId;
	this.tabId = 'vfChannelTab' + channelId;
	this.parentContainer = container;
	
	if(type == 'freeContent') {
		// TODO freeContent
	}
	else if(type == 'searchResults') {
		// TODO TEMP see if there's any need for something different
		this.sections = sections;
		this.sectionsLang = sectionsLang;
		this.sectionsType = sectionsType;
	}
	else {
		this.sections = sections;
		this.sectionsLang = sectionsLang;
		this.sectionsType = sectionsType;
	}
	
	this.sectionObjects = new Array();
	this.currentSection = 0;
	this.count = 0;
	this.keyword = '';
	this.baseUrl = base_url+'/ajax/media_get_nettitv_media';
//	this.baseUrl = base_url+'/dummy_vbbe';

	this.channel = 'all';
	this.sort_by = 'latestdesc';
	this.parentFinder = parentFinder;
	this.type = type; // thumbnails, thumbnailsExtra, freeContent, searchResults
	this.extraNid = false; // The nid of the extra tab. This is set after the tab is created, if we created an extra-type tab
	this.sectionsInitialized = false;
	
	var thisTab = this;
	
	/**
	 * videoFinderTab.initialize();
	 *
	 */
	 
	this.initialize = function(){
		//debugTime('Tab init');
		var html = '';
		var thisTab = this;
		this.channel = this.id;

		// add tab
		html = '';
		html += '<li id="' + this.container + 'Tab" class="vfTab">';
		html += '<a href="#"><span>';
		html += this.name;
		html += '</span></a>';
		html += '</li>';

		if(this.type == 'thumbnails') {
			$(this.parentContainer + ' ul.vfTabsLeft').append(html);	
		}
		else if(this.type == 'thumbnailsExtra') {
			$(this.parentContainer + ' ul.vfTabsRight').append(html);		
		}
		else if(this.type == 'freeContent'){
			// TODO
		}
		else if(this.type == 'searchResults') {
			$(this.parentContainer + ' ul.vfTabsLeft').append(html);	
		}
		else {
			return false;
		}

		// Add container
		html = '';
		html += '<div id="' + this.container + 'Sections"  class="vfSections '+this.type+'">';
		
		//Channel banner
		if( this.channelBanner ){
			if( this.type == 'thumbnailsExtra' ){
				html += '<div class="vfSection logo extraTab">';	
			}
			else{
				html += '<div class="vfSection logo">';
			}
			html += '<a href="'+this.channelUrl+'"><img border="0" src="'+this.channelLogo+'"/></a>';
			html += '<a class="linkText" href="'+this.channelUrl+'">'+this.channelLabel+'</a>';
			html += '</div>';
		}
		
		html += '</div>';

		$(this.parentContainer).append(html);

		// Section init code removed from here

	} // end function createTab
	
	
	/**
	 * Initializing the sections is slow on IE, so we'll do it only when we need to, instead of 
	 * when creating the Finder.
	 *
	 */
	 
	this.initSections = function() {
		// Add sections.
		
		var aLength = this.sections.length;
		
		for(i=0;i<aLength;i++){
			thisTab.sectionObjects[i] = new videoFinderSection(thisTab, thisTab.container, thisTab.sectionsType[i], thisTab.container+'Section'+i, thisTab.sections[i], thisTab.sectionsLang[i]);
		}		

		if(thisTab.mode == 'thumbnails') {
			$('#'+thisTab.tabId+' .vfSection.thumbnails').show();
			$('#'+thisTab.tabId+' .vfSection.series_list').hide();
		}
		else if(thisTab.mode == 'series_list') {
			$('#'+thisTab.tabId+' .vfSection.thumbnails').hide();
			$('#'+thisTab.tabId+' .vfSection.series_list').show();		
		}	
		
		this.sectionsInitialized = true;
	}
	
	/**
	 * videoFinderTab.loadAllSections()
	 *
	 */
	 
	this.loadAllSections = function(finder, shown){
		var html = '';
		var thisTab = this;
		var aLength = this.sectionObjects.length;

		for(i=0;i<aLength;i++){
			// TEMP check in place since we set this element to false in search
			if(thisTab.sectionObjects[i]) {
				thisTab.sectionObjects[i].loadSection();
			}		
		}
		
		if( vf_url_series_filter ){
			$('.vfSeriesFilterCurrent').html(urldecode(vf_url_series_filter));
			$('.vfSeriesFilter').show();
		}
		if( vf_url_series_group_filter ) {
			$('.vfSeriesFilterCurrent').html(urldecode(vf_url_series_group_filter));
			$('.vfSeriesFilter').show();
		}
	}


	this.updateSorting = function(sort_by){
		this.sort_by = sort_by;
	}


	this.updatePaging = function(){
		
	}


	this.initialize();
	
} // end function videoFinderTab


/**
 * Section object
 *
 */
 
function videoFinderSection(parentTab, container, type, sectionId, section, sectionLang) {
	this.parentTab = parentTab;
	this.container = container;
	this.sectionId = sectionId;
	this.section = section;
	this.sectionLang = sectionLang;
	
	this.pagingLimit = VF_PAGING_LIMIT_LESS;
	this.mode = 'less'; // more/less:Are we showing 8 or 16 thumbnails on a page
	
	this.pagingOffset = 0;
	this.pagingCurrentPage = 1;
	this.type = type;
	this.parentFinder = parentTab.parentFinder;
//	this.showable = true;
	
	var thisSection = this;
	
	this.initialize = function() {
		//debugTime('section '+this.sectionId+' init start');
		var html = '';
		
		html += '<div id="'+this.sectionId+'" class="vfSection '+this.type+' '+this.section+'">';
		html += '<h4><a href="#" class="more">' + sectionLang + '</a></h4>';
		html += '<img src="http://n.sestatic.fi/sites/all/themes/nelonen/img/icon-loading.gif" class="vfLoader" id="' + this.sectionId + 'Loader' +  '" />';
		html += '<ul class="payload">';
		//debugTime('section init b loop');		
		if(this.type == 'thumbnails' && this.parentTab.type != 'searchResults') {
			for(var i = 0; i < this.pagingLimit;i++) {
				html += DUMMYITEM;
			}
		}
		//debugTime('section init a loop');				
		html += '</ul>';
		html += '\
			<div class="clearFix">\
				<ul class="vfPaging pagination" style="float: left;">&nbsp;</ul>\
				\
				<div class="vfMoreLess vfMore"><a href="' + i + '" >Lisää</a></div>\
				\
				<div class="vfMoreLess vfLess"><a href="' + i + '" >Vähemmän</a></div>\
			</div>';
		html += '</div>';

		$('#'+this.container+'Sections').append(html);
		//debugTime('section init a append');
		
		$('#'+this.sectionId+' .vfMore').click(function() {
			thisSection.mode = 'more';
			thisSection.pagingLimit = VF_PAGING_LIMIT_MORE;
			thisSection.loadSection();
			thisSection.parentTab.parentFinder.updateCookie();
			return false;
		});
		
		$('#'+this.sectionId+' .vfLess').click(function() {
			thisSection.mode = 'less';
			thisSection.pagingLimit = VF_PAGING_LIMIT_LESS;
			thisSection.loadSection();
			thisSection.parentTab.parentFinder.updateCookie();
			return false;
		});
		//debugTime('section init end');
	}
	
	
	/**
	 * Loads a single section
	 *
	 */
	 
	this.loadSection = function() {
		console.log('loading section');
		var containerId = '#'+thisSection.sectionId;
		var loaderId = containerId+'Loader';
		var resultContainerId = containerId + ' ul.payload';

		if(this.parentTab.type == 'searchResults') {
			// Nothing to load for search results sections unless a search is made.
			//$(resultContainerId).html('');
			return false;
		}

		// Show loader for sections not being loaded in the background
		var shown = $(containerId).is(':visible');
		if(shown) {
			$(loaderId).show();
		}
		
		if(thisSection.type == 'thumbnails') {
			// Prevent jumping when emptying the container and getting new content

			var height = $(resultContainerId).height();

			$(resultContainerId).css('height', height);
			$(resultContainerId).empty();

			$.getJSON(this.constructRequestUrl(), function(json){

				html = '';
				
				var totalLength = json.total_count;
				
				if(json.programme_group){
					thisSection.parentTab.parentFinder.setSubCategories(json.programme_group);
				}
				
				if(json.video.length > 0) {
					mediaData = json.video;
				}
				else if(json.video_episode.length > 0) {
					mediaData = json.video_episode;				
				}
				else if(json.audio.length > 0 ){
					mediaData = json.audio;
				}
				else {
					mediaData = false;
				}
				aLength = mediaData.length;

				if(aLength == 0 || typeof(aLength) == 'undefined'){					
					$(resultContainerId).html('<li class="noContent"><span	>Ei sisältöä</span></li>')
	
					// With the series filter, we can't allow a section on the "all" tab
					// to get hideMe, since then we wouldn't see the section even after 
					// clearing the filter.
					//if(thisSection.parentTab.channel != 'all') {
					//	$(containerId).addClass('hideMe');					
					//}
					
					if(thisSection.parentTab.parentFinder.seriesFilter == '__' && thisSection.parentTab.parentFinder.seriesGroupFilter == '__') {
						$(containerId).hide(500);
					}
				} 
				else {
					for(j=0;j<aLength;j++){				
						html += thisSection.createListElement(mediaData[j], false);
					}	
					$(resultContainerId).append(html);			
				}
				
				$(resultContainerId).css('height', '');
				$(loaderId).hide();
	
				// Pagination
				if(thisSection.mode == 'less') {
					// Show "lisaa" button if there are more than 8 items
					if(aLength < 8 || typeof(aLength) == 'undefined'){
						$('#'+thisSection.sectionId+' .vfMore').hide();
						$('#'+thisSection.sectionId+' .vfLess').hide();
					}
					else{
						$('#'+thisSection.sectionId+' .vfMore').show();
						$('#'+thisSection.sectionId+' .vfLess').hide();
					}
					//Hide pagination
					$('#'+thisSection.sectionId+' .vfPaging').hide();
				}
				else if(thisSection.mode == 'more') {
					$('#'+thisSection.sectionId+' .vfMore').hide();
					$('#'+thisSection.sectionId+' .vfLess').show();
					$('#'+thisSection.sectionId+' .vfPaging').show();
					
					thisSection.pagination(VF_PAGING_LIMIT_MORE, totalLength);
				}
				
				// Hover descriptions
				if($('#'+thisSection.sectionId+' a.imgLink').length) {
					$('#'+thisSection.sectionId+' a.imgLink').tooltip({track: true,delay: 0,showURL: false,fixPNG: true,showBody: " ---- ",extraClass: "pretty fancy",top: 10,left: 10});
				}
console.log('end GET call for '+thisSection.sectionId+' '+thisSection.type);
			});
		}
		else if(thisSection.type == 'series_list') {
			var html = this.generateSeriesList(thisSection.sectionId, thisSection.parentFinder);
			$(resultContainerId).append(html);

		}
		

	}
	
	/**
	 * videoFinderSection.createListElement()
	 *
	 * Creates a list element to be appended to an ul
	 *
	 */
	 
	this.createListElement = function(inputMediaData, searchData){
		var href = thisSection.parentFinder.targetPage;	
	
		if(inputMediaData) {
			var mediaData = inputMediaData;
			mediaData['nodeurl'] = href+'?vt='+mediaData['media_type']+'&vid='+ mediaData['video_id_to_use'];
		}
		else if(searchData) {
			// Take the data returned by the search backend, and format it to look
			// like a mediaData element, so we can use the same HTML generator.

			mediaData = new Array();
			mediaData['video_datetime_to_use'] = searchData['modified'];
			mediaData['age_limit'] = false;
			mediaData['video_ready'] = 1; // The search should only return ready videos. TODO check
			mediaData['video_id_to_use'] = false; // TODO are we even getting anything but the mid? TODO check and fix
			mediaData['video_description_teaser'] = searchData['teaser'].substr(0,100);
			
			if(mediaData['video_description_teaser'].length < searchData['teaser'].length) {
				mediaData['video_description_teaser'] += '...';
			}

			mediaData['video_name_to_use'] = searchData['title'];
			mediaData['viewable_until_formatted'] = '';
			mediaData['video_id_to_use'] = false;// TODO
			mediaData['video_series_name_to_use'] = false; // TODO
			
			mediaData['nodeurl'] = base_url+'/'+searchData['nodeurl']
			
			mediaData['video_thumbnail_to_use'] = false; // TODO
		}
		else {
			// These are for the dummy spacer items
			mediaData = new Array();
		}

		var html = '';
		html += '<li class="vfItem">';
		
		if(mediaData['video_censored'] == 1 ){
			var action = ' onclick="return false;" href="#"';
			var title = mediaData['video_censored_reason'];
			var restricted = true;
			var ageLimit = false;
		}/*
		else if( mediaData['age_limit'] > userData['age'] ){
			var action = ' onclick="return false;" href="#"';
			var title = 'Tämä video on kielletty alle '+mediaData['age_limit']+'-vuotiailta';
			var restricted = true;
			var ageLimit = '<img height="43" width="43" class="iconRestricted" src="'+static_base_url+'/sites/all/themes/nelonen/img/icon-restricted.png" alt="K'+mediaData['age_limit']+'" />';
			ageLimit += '<div class="restrictedAge"><span>K'+mediaData['age_limit']+'</span></div>';
		}*/
		else if( mediaData['video_ready'] == 0){
			//Only consistent info for episodes to calculate ETA on conversion
			if( mediaData['program_episode_starttime'] && mediaData['program_episode_duration'] ){
				var conversionEta = eta( mediaData['program_episode_starttime'], mediaData['program_episode_duration']);
				var title = 'Tämä video on katsottavissa noin kello '+conversionEta.toTimeString().substr(0,5)+'.';
			}
			else{
				var title = 'Tämä video on saatavilla hetken kuluttua ohjelman TV-esityksen päättymisestä.';
			}
			var action = ' onclick="return false;" href="#"';
			var restricted = true;
			var ageLimit = false;
		}
		else {
			var action = ' href="'+mediaData['nodeurl']+'"';
			var title = mediaData['video_description_to_use'];
			var restricted = false;
			var ageLimit = false;
		}
		
		html += '<a class="imgLink" title="'+mediaData['video_name_to_use']+' ---- '+title+'"'+action+'>';
		if(restricted) {
			html += '<div class="restricted">';
			if(ageLimit) {
				html += ageLimit;
			}			
			html += '</div>';
		}

		html += '<img src="'+mediaData['video_thumbnail_to_use']+'" alt="'+mediaData['video_name_to_use']+'" 	/></a>';		
		

		html += '<ul class="nettiItemDesc">';

		var geo = '';
		if( mediaData['program_geoblock'] == 0 ){
			geo = '<img src="'+static_base_url+'/sites/all/themes/nelonen/img/geo_bw.png" width="16" height="14" class="geoIcon" /></span>';
		}

		if(restricted){
			html +=	'<li class="timeStamp"><span class="time">'+mediaData['video_datetime_to_use']+'</span>'+geo+'</li>';
			html +=	'<li class="name">'+mediaData['video_name_to_use']+'</li>';
		}
		else{
			html +=	'<li class="timeStamp"><span class="time">'+mediaData['video_datetime_to_use']+'</span>';
			if(mediaData['media_type_id'] == 3){
				html +=	'<span class="timeLeft"><a href="'+mediaData['audio_file_path_get_file_script']+'">Lataa mp3</span></a></li>';
			}
			else{
				html += geo+'<span class="timeLeft">'+mediaData['viewable_until_formatted']+'</span></li>';
			}	
			html +=	'<li class="name">'+'<a href="'+mediaData['nodeurl']+'">'+mediaData['video_name_to_use']+'</a></li>';
		}
		
		html += '<li class="description">';
		html += '<p>'+mediaData['video_description_teaser']+'</p>';
		//add optional_link_address to description if any
		if (mediaData['optional_link_address'] && mediaData['optional_link_text']){
			html += '<p class="optionalLink"><a href="'+mediaData['optional_link_address']+'">'+mediaData['optional_link_text']+'</a></p>';
		}
		html += '</li>';//close the description
		
		html += '<li class="seriesMore">Näytä lisää: <a href="#" class="vfSeriesMore">'+mediaData['video_series_name_to_use']+'</a></li>';
		html += '</ul></li>';
		html += '</li>';

		return html;		
	}	
	
	
	/**
	 * @param $channel String Channel filter, use "all" to not filter the results.
	 * @param $type String Media type filter, allowed values are "all", "video", "video_episode"
	 * @param $programme String Programme name, use "__" to not use.
	 * @param $sort String Sort by what? Use "latest", "least_watched", "least_commented", "latestDESC", "most_watched", "most_commented"
	 * @param $offset Integer
	 * @param $limit Integer
	 * @param $json String Set to "true" to return a string of JSON encoded data, 'false' to return an array.
	 * @param $programmeGroup String 
	 *			set to '__' to tell function return videos for $programme (if $programme is set)
	 *			set to programme group name if you want to function 
	 * 				to return videos belong to the programme group (when $programme='__').
	 *			if $programme and $programmGroup are set at the same time 
	 *				=> return videos belongs to $programme and extra info about $programmeGroup
	 *
	 * @param $extraTabNid String extra tab node nid where the wordsId is fetch to filter 
	 * 		the video/video episode. Note that this only applied when $programme = "__". 
	 * 		If this is set to 0, then the function will not return data for extra tab
	 *
	 */
	 
	this.constructRequestUrl = function(){
		var url = this.parentTab.baseUrl;
		
		if(this.parentTab.type == 'thumbnails') {
			url += '/' + this.parentTab.channel;
			url += '/' + this.section;
			
			// Force series filter
			if(this.parentTab.parentFinder.forcedSeriesFilter) {
				url += '/' + urlencode(this.parentTab.parentFinder.forcedSeriesFilter);			
			}
			else {
				url += '/' + urlencode(this.parentTab.parentFinder.seriesFilter);
			}
			
			url += '/' + this.parentTab.sort_by;
			url += '/' + this.pagingOffset;
			url += '/' + this.pagingLimit;
			url += '/true';// return JSON
			
			// Force series group filter
			if(this.parentTab.parentFinder.forcedSeriesGroupFilter) {
				url += '/' + urlencode(this.parentTab.parentFinder.forcedSeriesGroupFilter);			
			}
			else {
				url += '/' + urlencode(this.parentTab.parentFinder.seriesGroupFilter);			
			}
			url += '/__'; // No extra tab
			url += '/'+this.parentTab.parentFinder.geoBlockFilter;

		}
		else if(this.parentTab.type == 'thumbnailsExtra') {
			url += '/all';
			url += '/' + this.section;
			url += '/__'; // No series filter here
			url += '/' + this.parentTab.sort_by;
			url += '/' + this.pagingOffset;
			url += '/' + this.pagingLimit;
			url += '/true';// return JSON
			url += '/__'; // No series group filter
			url += '/'+this.parentTab.extraNid;
			url += '/'+this.parentTab.parentFinder.geoBlockFilter;
		}
		
		return url;
	}
	
	
	/**
	 * @param limit Integer The current limit for this section
	 * @param length Integer The total amount of items available, returned in the JSON data.
	 *
	 */
	 
	this.pagination = function(limit, length){
		//number of pages
		var noPages = Math.ceil(length/limit);
		var currentPage = this.pagingCurrentPage;
	
		console.log('l- '+length);
		console.log('p- '+noPages);
	
		var thisSection = this;
	
		//active class for first page
		if(currentPage == 1){
			var activeClass = ' class="active"';
		}
		else{
			var activeClass = '';
		}
	
		var navOutput = '<li><a'+activeClass+' href="0">1</a></li>';
	
		if(noPages > 1){
			if(noPages > 7){
				if(currentPage <= 4){
					for( i=2; i < 7; i++){
						offset = (i-1) * limit;
						//active class for current page
						if((currentPage-1) * limit == offset){
							activeClass = ' class="active"';
						}
						else{
							activeClass = '';
						}
						navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
					}
					navOutput += '<li class="rightDot">...</li>';
				}
				else if(currentPage >= (noPages - 4)){
					var pageFrom = noPages - 5;
					var pageTo = noPages;
		
					navOutput += '<li class="leftDot">...</li>';
					for( i=pageFrom; i < pageTo; i++){
						offset = (i-1) * limit;
						//active class for current page
						if((currentPage-1) * limit == offset){
							activeClass = ' class="active"';
						}
						else{
							activeClass = '';
						}
						navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
					}
				}
				else{
					var pageFrom = currentPage - 2;
					var pageTo = pageFrom + 5;
		
					navOutput += '<li class="leftDot">...</li>';
					for( i=pageFrom; i < pageTo; i++){
						offset = (i-1) * limit;
						//active class for current page
						if((currentPage-1) * limit == offset){
							activeClass = ' class="active"';
						}
						else{
							activeClass = '';
						}
						navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
					}
					navOutput += '<li class="rightDot">...</li>';
				}
			}
			else{
				for(i=2; i < noPages; i++){
					if( i==1 ){
						offset = 0;
					}
					else{
						offset = (i-1) * limit;
					}
					if(currentPage == i){
						activeClass = ' class="active"';
					}
					else{
						activeClass = '';
					}
					navOutput += '<li><a'+activeClass+' href="'+offset+'">'+i+'</a></li>';
				}
			}
		
			//active class for last page
			if(currentPage == noPages){
				activeClass = ' class="active"';
			}
			else{
				activeClass = '';
			}
			navOutput += '<li><a'+activeClass+' href="'+(noPages-1)*limit+'">'+noPages+'</a></li>';
			$('#'+thisSection.sectionId+' .vfPaging').html(navOutput);
			$('#'+thisSection.sectionId+' .vfPaging').show();
		}
		else{
			$('#'+thisSection.sectionId+' .vfPaging').hide();
		}
	
		//register pagination clicks
		$('#'+thisSection.sectionId+' .pagination li a').click( function() {
	
			//get the offset
			var offset = $(this).attr('href');
	
			if( offset.indexOf('/') ) {
				offset = offset.substr(offset.lastIndexOf('/')+1);
			}
			
			thisSection.pagingOffset = offset;
			thisSection.pagingCurrentPage = (offset/limit)+1;
			thisSection.loadSection();
			thisSection.parentTab.parentFinder.updateCookie();
			
			return false;
		});
	}	
	
	
	/**
	 * Generates the HTML for the list of series
	 *
	 */
	
	this.generateSeriesList = function(containerId, finder) {
		$.get(base_url+"/ajax/media_get_netti_tv_series_list/"+thisSection.parentTab.channel+"/false", function(data) {
		 	data = eval("("+data+")");

			//If forced channel filter, return only a suggestion list of that channel
			if( vf_show_tab_channel_id ){
				var temp = data;
				// Pregenerate lowercase names for matching in the series suggester
			 	for(var i = 0;i<temp.length;i++) {
			 		temp[i]['name_lowercase'] = temp[i]['name'].toLowerCase();
			 	}
				this.seriesFilter = temp;
			}

			//column size
			var listLength = data.length;
			var colSize = Math.ceil(data.length/4);
			var colSizeBase = colSize;
			var colSizeUpper = colSize;
			
			var list = '';
			
			if( data.length == 0 ){
				list += '<h4>Ei sarjoja.</h4>';
			}

			if( listLength > 0 ){
				if( listLength <= 10 ){
					colSize = data.length-1;
				}
				list += '<h4>Sarjat</h4><ul class="vfSeriesList">';
				for(var i=0; i<=colSize; i++){
					if(i==0){
						lastFirstChar = data[i]['name'].toLowerCase().charAt(0);
						list += '<li>&nbsp;</li>';
						list += '<li class="title">'+data[i]['name'].toLowerCase().charAt(0)+'</li>';
					}
					else{
						lastFirstChar = data[i-1]['name'].toLowerCase().charAt(0);
					}
					currentFirstChar = data[i]['name'].toLowerCase().charAt(0);
					if( currentFirstChar != lastFirstChar ){
						list += '<li>&nbsp;</li>';
						list += '<li class="title">'+data[i]['name'].charAt(0)+'</li>';
					}

					if(data[i]['is_group'] == 1){
						group = 'group';
						browserLink = vf_netti_url+'?video_browser_series_group_filter='+data[i]['url_encode_name'];
					}
					else {
						group = '';
						browserLink = vf_netti_url+'?video_browser_series_filter='+data[i]['url_encode_name'];
					}
					
					if( data[i]['override'] == null ){
						list += '<li><a href="'+browserLink+'" class="'+group+'" id="'+data[i]['url_encode_name']+'">'+data[i]['name']+'</a></li>';
					}
					else{
						list += '<li title="'+data[i]['name']+' ---- Tämän sarjan jaksoja ei ole nähtävillä verkossa, sillä sarjalle ei ole verkkoesitysoikeuksia" class="overrideSeries">'+data[i]['name']+'</li>';
					}	
				}
				list += '</ul>';
			}
			if( listLength > 10 ){
				//2 cols
				if( listLength <= 20 ){
					colSizeUpper = data.length-1;
				}
				else{
					colSizeUpper = colSizeBase*2;
				}
				list += '<ul class="vfSeriesList">';
				for(var i=colSizeBase+1; i<=colSizeUpper; i++){
					lastFirstChar = data[i-1]['name'].toLowerCase().charAt(0);
					currentFirstChar = data[i]['name'].toLowerCase().charAt(0);
					if( currentFirstChar != lastFirstChar ){
						list += '<li>&nbsp;</li>';
						list += '<li class="title">'+data[i]['name'].charAt(0)+'</li>';
					}
					if(data[i]['is_group'] == 1){
						group = 'group';
						browserLink = vf_netti_url+'?video_browser_series_group_filter='+data[i]['url_encode_name'];
					}
					else {
						group = '';
						browserLink = vf_netti_url+'?video_browser_series_filter='+data[i]['url_encode_name'];
					}
					if( data[i]['override'] == null ){
						list += '<li><a href="'+browserLink+'" class="'+group+'" id="'+data[i]['url_encode_name']+'">'+data[i]['name']+'</a></li>';
					}
					else{
						list += '<li class="overrideSeries">'+data[i]['name']+'</li>';
					}	
				}
				list += '</ul>';
			}
			if( listLength > 20){
				//3 cols
				if( listLength < 30 ){
					colSizeUpper = data.length-1;
				}
				else{
					colSizeUpper = colSizeBase*3;
				}
				list += '<ul class="vfSeriesList">';
				for(var i=colSizeBase*2+1; i<=colSizeUpper; i++){
					lastFirstChar = data[i-1]['name'].toLowerCase().charAt(0);
					currentFirstChar = data[i]['name'].toLowerCase().charAt(0);
					if( currentFirstChar != lastFirstChar ){
						list += '<li>&nbsp;</li>';
						list += '<li class="title">'+data[i]['name'].charAt(0)+'</li>';
					}
					if(data[i]['is_group'] == 1){
						group = 'group';
						browserLink = vf_netti_url+'?video_browser_series_group_filter='+data[i]['url_encode_name'];
					}
					else {
						group = '';
						browserLink = vf_netti_url+'?video_browser_series_filter='+data[i]['url_encode_name'];
					}
					if( data[i]['override'] == null ){
						list += '<li><a href="'+browserLink+'" class="'+group+'" id="'+data[i]['url_encode_name']+'">'+data[i]['name']+'</a></li>';
					}
					else{
						list += '<li title="'+data[i]['name']+' ---- Tämän sarjan jaksoja ei ole nähtävillä verkossa, sillä sarjalle ei ole verkkoesitysoikeuksia" class="overrideSeries">'+data[i]['name']+'</li>';
					}	
				}
				list += '</ul>';
			}
			if( listLength > 30 ){
				list += '<ul class="vfSeriesList">';
				for(var i=colSizeBase*3+1; i<=data.length-1; i++){
					lastFirstChar = data[i-1]['name'].toLowerCase().charAt(0);
					currentFirstChar = data[i]['name'].toLowerCase().charAt(0);
					if( currentFirstChar != lastFirstChar ){
						list += '<li>&nbsp;</li>';
						list += '<li class="title">'+data[i]['name'].charAt(0)+'</li>';
					}
					if(data[i]['is_group'] == 1){
						group = 'group';
						browserLink = vf_netti_url+'?video_browser_series_group_filter='+data[i]['url_encode_name'];
					}
					else {
						group = '';
						browserLink = vf_netti_url+'?video_browser_series_filter='+data[i]['url_encode_name'];
					}
					if( data[i]['override'] == null ){
						list += '<li><a href="'+browserLink+'" class="'+group+'" id="'+data[i]['url_encode_name']+'">'+data[i]['name']+'</a></li>';
					}
					else{
						list += '<li title="'+data[i]['name']+' ---- Tämän sarjan jaksoja ei ole nähtävillä verkossa, sillä sarjalle ei ole verkkoesitysoikeuksia" class="overrideSeries">'+data[i]['name']+'</li>';
					}	
				}
				list += '</ul>';
			}

			$('#'+containerId).html(list);

			//Tool tip for unavailable series
			if( $('li.overrideSeries', $('#videoFinder')).length ){
				//tooltip settings
				$('li.overrideSeries', $('#videoFinder')).tooltip({track: true,delay: 0,showURL: false,fixPNG: true,showBody: " ---- ",extraClass: "pretty fancy",top: 10,left: 10});
			}

			//register clicks on program list links
			$('.vfSeriesList li a').click( function() {
	      		finder.setSeriesFilter(finder, $(this));
				
				return false;
			});
		});
	
	}
	
	this.initialize();
} // end function videoFinderSection

function isEmpty(obj) {
	for(var prop in obj) {
		if(obj.hasOwnProperty(prop))
			return false;
	}
	return true;
}

$(document).ready(function() {
	media_finder_select_programme_and_channel();
});

function media_finder_select_programme_and_channel(){
	var programmeSelectVal = $("#edit-filter-by-programme").val();
	var programmeGroupSelectVal = $("#edit-filter-by-programme-group").val();
	var channelSelectVal = $("#edit-filter-by-channel").val();
	
	//if any of them is selected => do not check the show tab
	if (programmeSelectVal!='' || programmeGroupSelectVal!='' || channelSelectVal!=0){
		channelSelectVal = $("#edit-show-tabs").attr('checked',false);
	}
}

function eta(start, duration) {
	//calculate eta of video conversion
	var parts = start.split(' ');
	var dateParts = parts[0].split('-');
	var timeParts = parts[1].split(':');
	dateParts[1] = dateParts[1] - 1;

	var eta = new Date(dateParts[0],dateParts[1],dateParts[2],timeParts[0],timeParts[1],timeParts[2]);
	extraTime = parseInt(duration) + (parseInt(duration) * 0.8) + 5;
	eta.setMinutes(eta.getMinutes() + extraTime);
		
	return eta;		
}



function urlencode (str) {
    // URL-encodes string  
    // 
    // version: 911.718
    // discuss at: http://phpjs.org/functions/urlencode    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    str = (str+'').toString();
        // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function urldecode (str) {
	str = (str+'').toString();
	
	return decodeURIComponent(str).replace(/%21/g, '!').replace(/%27/g, '&#39;').replace(/%28/g, '&#40;').
                                                                    replace(/%29/g, '&#41;').replace(/%2A/g, '#').replace(/\+/g, '&#32');
}