/*
 * Fallback if console.log() does not exist - http://ajax-prototype.blogspot.com/2006/12/workaround-to-make-firebug-consolelog.html
 *
 */
try { console.log('init console... done'); } catch(e) { console = { log: function(str) {
	$('#debug').append(str+'<br/>');
} } }

var user = false;
var data = 0;

$(document).ready(function(){

  	//Check the user's login status
 	var sid = $.cookie(sessionName);
 	var userData = $.cookie('userData');
 	userDataO = eval('(' + userData + ')');
 	if(userData === null) {
 		var userDataO = new Object();
		userDataO['age'] = 0;
 	}
	window.userData = userDataO;

	if (!sid) {
		//The user has not yet received a cookie (maybe because they've made a request to a cached page)
		//Let's get one from Drupal
		$.get(drupalUrl+'get_cookie');
	}

 	var t = new Date();
 	var currentTime = Math.round(t.getTime()/1000);

 	// Add click handlers on the dummy comment form for fetching the real one
 	get_comment_form();

 	if (userData && sid) {
 		//All cookies available, check if there really is a session
 		var success = true;
 		try {
 			var tmp = JSON.parse(userData, function(key, value) {
 				if (typeof value == "string") {
 					//Make sure spaces get in the object correctly
 					return value.replace(/\+/g," ");
 				}
 				return value;
 			});
 		}
 		catch (e) {
 			success = false;
 		}

 		if (success) {
 			$.ajax({
 				type: "GET",
 				url: fileDirectory+"sessions/"+sid,
 				complete: function(xhr, textStatus) {
					if (xhr.status == 200) {
						user = tmp; //Make user object available

						// Manipulate the login items to show the logged in status
						if(user) {
							$('#loggedStatus').html(user.display_name);
							$('#logout').show();
							$('.showToUser'+user.id).show();
						}
						else {
							$('#login').show();
							$('.login').show();
					 		$('.showToAnon').show();
						}
 					}
 					else {
 						//No session, we remove the lingering cookie so that we won't have to do this check again
 						var time = new Date();
 						time.setTime((currentTime - 72000)*1000);
 						$.cookie('userData', null, { path: '/', expires: time});

						$('#login').show();
						$('.login').show();
				 		$('.showToAnon').show();
 					}
 				}
 			});
 		}
 		else {
			$('#login').show();
			$('.login').show();
	 		$('.showToAnon').show();
 		}
 	}
 	else {
		$('#login').show();
		$('.login').show();
 		$('.showToAnon').show();
 	}

 	var isAdmin = $.cookie('isAdmin');
 	if(isAdmin == 1) {
		$('#loggedStatus').html('admin');
		$('#login').hide();
		$('.login').hide();
		$('#logout').hide();
		$('#adminLogout').show();
		// Added 2010-06-13:
 		$('.showToAnon').hide();
 	}

 	var isEditor = $.cookie('isEditor');
 	if(isEditor == 1) {
		$('.nodeEditLink').show();
		$('.multipleNodeEditLink').show();
		$('.internalNodeEditLink').show();
		$('.mediaEditLink').show();
		$('.showToEditor').show();
 	}

 	var isAuthenticated = $.cookie('isAuthenticated');
 	if(isAuthenticated == 1) {
 		$('.showToAuthenticated').show();
 	}
 	
 	var hasRole = $.cookie('hasRole');
 	if(hasRole == 1 || isAdmin == 1) {
		$('.showToHasRole').show();
	}
 	
 	var reAllowAnonSubmission = $.cookie('reAllowAnonSubmission');
 	if(reAllowAnonSubmission == 1) {
 		$('#userSubmissionButton').show();
 		$('#requireUserToLogIn').hide();
 	}

 	if ($(".updown-vote").length > 0) {

 		userVotedIds = $.cookie('voted');

 		if(userVotedIds !== null) {
 			userVotedIds = userVotedIds.split(",");

 			uvotedCheckList = new Array();
 			uvotedScore = new Array();

 			for (var i in userVotedIds) {
 				uvoted = userVotedIds[i].split(";");
 				uvotedCheckList.push(uvoted[0]+'-'+uvoted[1]);
 				uvotedScore.push(uvoted[2]);
 			}

 			$(".updown-vote").each(function () {

 				elementId = $(this).parent().attr('id');
 				elementIdSplit = elementId.split("-");
 				uvotedIndex = $.inArray(elementIdSplit[2]+"-"+elementIdSplit[3], uvotedCheckList);

 				if(uvotedIndex != -1) {
 					$(this).parent().removeClass('updown-widget-voting');
 					$(this).parent().addClass('updown-widget-voted');

 					if(uvotedScore[uvotedIndex] == 1) {
 						$(this).find(".updown-voteup a").each(function() {
 							$(this).addClass('voted');
 						});
 						$(this).find(".updown-votedown a").each(function() {
 							$(this).addClass('votingDisabled');
 						});
 					}
 					else if(uvotedScore[uvotedIndex] == -1) {
 						$(this).find(".updown-voteup a").each(function() {
 							$(this).addClass('votingDisabled');
 						});
 						$(this).find(".updown-votedown a").each(function() {
 							$(this).addClass('voted');
 						});
 					}
 				}

 			});

 		}

 	}
 	 	
 	//Check if there is a full page ad and if we should show it
 	if ($("#fullPageAd").length > 0) {
 		adHistory = $.cookie("adHistory");
 		var showAd = false;

 		if (adHistory) {
 			var shownAds;
 			try {
 				var shownAds = JSON.parse(adHistory);
 			}
 			catch (e) {
 				//Some garbage in cookie, let's assume there's no cookie at all
 				showAd = true;
 				shownAds = {};
 			}

 			if (typeof shownAds[currentUrl] == "undefined") {
 				//Ad not shown on this page before
 				showAd = true;
 			}
 			else {
 				//Ad shown before, let's check if we can show it again
 				var interval = $("#adInterval").html();
 				if (currentTime - shownAds[currentUrl] > interval) {
 					showAd = true;
 				}
 			}
 		}
 		else {
 			//No cookie
 			showAd = true;
 			var shownAds = {};
 		}

 		if (showAd) {
 			//The judge has ruled that the advertisement should be shown. Let's get to business
 			var adElem = $("#fullPageAd");
 			//Get the delay (amount of time the ad will be shown)
 			var delay = $("#adDelay").html();

 			//Hide everything else on the page and show the ad overlay
			$("#topSegment, #contentWrap, #footerHolder, body.programInfo, .smalltopnavi").hide();
			//Store current style attribute of body element
			var oldStyle = $("body").attr("style");
			//This ensures that the background color of the full page ad div extends on the whole page
			$("html, body").css("background", adElem.css("background"));

			$("#fullPageAdContainer, #fullPageAd, #fullPageAd img").show();


			var adWidth = adElem.width();

 			function tunePromoBox() {
				var promoElem = $("#fullPageAdPromoBox");

				var adHeight = $(window).height();
				var promoHeight = promoElem.height();
				var promoWidth = promoElem.width();

				//y-coordinate for the box
				if (promoElem.hasClass('top')) {
					//The box is above the horizontal center line
					var promoTop = Math.ceil(adHeight/2 - promoHeight);
				}
				else {
					var promoTop = Math.ceil(adHeight/2);
				}

				//x-coordinate for the box
				var padding = Math.ceil((adWidth/2 - promoWidth)/2); //The box needs to be centered between the border of the ad and the vertical center line (either left or right to the centerline)
				if (promoElem.hasClass('left')) {
					var promoLeft = padding;
				}
				else {
					var promoLeft = Math.ceil(adWidth/2 + padding);
				}

				//adElem.append(promoElem);
				promoElem.css({'position' : 'absolute', 'z-index' : '1500', 'background' : '#ffffff', 'top' : promoTop, 'left' : promoLeft});
 			}

			//Show the promo box, if there is one
			if ($("#fullPageAdPromoBox").length > 0) {
				tunePromoBox();
				$(window).resize(tunePromoBox);
			}
			else {
				//Otherwise, show the navigation
				$(".smalltopnavi").show();
			}

			//Make the ad go away after the set delay
			window.setTimeout('$("html").attr("style", ""); $("body").attr("style", "'+oldStyle+'"); ' +
							  '$("#topSegment, #contentWrap, #footerHolder, body.programInfo, .smalltopnavi").show(); $("#fullPageAdContainer").hide(); $(window).unbind("resize")',
							  delay*1000);

			//Refresh the cookie
			shownAds[currentUrl] = currentTime;

 			jsonContent = JSON.stringify(shownAds);
 			var d = new Date();
 			d.setTime(t.getTime() + 2592000000) //One month

 			$.cookie('adHistory', jsonContent, { path: '/', expires: d});
 		}
 	}
 	
 	$("#fullPageAD a").click(function(){
		$("#fullPageAD").remove();
	});
	
	if($("#fullGuide").length) {
		$("#topScrollContent").width($("#fullGuide").width()+2);
	}
	$("#topScroll").scroll(function(){
		$("#fullGuideScroller").scrollLeft($("#topScroll").scrollLeft());
	});
	
	$("#fullGuideScroller").scroll(function(){
		$("#topScroll").scrollLeft($("#fullGuideScroller").scrollLeft());
	});


	setAutoGrow();

	//Adds contentBox class to promo_box_simple, flat list as a unit of its own
	if( $('.contentBoxCheck').length ){
		$('.contentBoxCheck').each( function() {
			if( $(this).parents().hasClass('contentBox') ){
			}
			else{
				$(this).addClass('contentBox');
			}
		});
	}


 	//Set comment form focus handlers (to get actual comment forms when this page is cached)
	var commentElem = $("#comment-form");

	// Code handling logged in users moved to the function that has var user defined.

	//remove padding from comment links
	$('.links li').each(function(){
		$(this).css('padding-left', '0px');
	});


	//hide textarea label
	$('#edit-comment-wrapper > label').css('display', 'none');


	//Position submit button based on comment form
	$('.comments form').each( function() {
		if( !$('.captcha', $(this)).length ) {
			//Mini comment box so re position button
			$('.submit-dummy').addClass('correctPos');
		}
	});

	$('#comment-form').each( function() {
		if( !$('.captcha', $(this)).length ) {
			//Mini comment box so re position button
			$('.submit-dummy').addClass('correctPos');
		}
	});


 	if(screen.width == 1024) {
		$("#sideTab").hide();
	}

 	//style first and last category boxes
 	$('.categoryBox:first').addClass('categoryFirstBox');
 	$('.categoryBox:last').addClass('categoryLastBox');

 	//competition form validation
 	$(".submitCEButton").bind("click", function() {
 		var formId = $(this).parent().parent().attr('id'); 

 		//empty current error message if they exist
 	 	$('#'+formId+' em').empty();
		
 	 	//check all mandatory fields are filled
 	 	var result = mandatoryFields($('#'+formId));

 	 	if(!result){
 	 		var prgA = true;
 	 		var prgB = true;
 	 		var prgC = true;

	 		//get each input and check classes (text)
	 		$('#'+formId+' input').each( function() {
	 			var arrayOfClasses = $(this).attr('class').split(' ');
				for(var i=0; i<arrayOfClasses.length; i++) {
					if(arrayOfClasses[i] == 'maxval' ) {
						prgA = checkMaxVal(arrayOfClasses[i+1], $(this));
					}
					if(arrayOfClasses[i] == 'minval' ) {
						prgB = checkMinVal(arrayOfClasses[i+1], $(this));
					}
				}
			});

			//get each textarea and check classes
	 		$('#'+formId+' textarea').each( function() {
	 			var arrayOfClasses = $(this).attr('class').split(' ');
				for(var i=0; i<arrayOfClasses.length; i++) {
					if(arrayOfClasses[i] == 'maxlength' ) {
						prgC = checkMaxLength(arrayOfClasses[i+1], $(this));
					}
				}
	 		});

	 		if(!prgA || !prgB || !prgC){
	 			return false;
	 		}
	 		else{
	 			mySubmit(formId)
	 		}

 		}
 		else{
 			return false;
 		}
 		
 	});

 	//Handling reporting offensive comments
 	$(".reportCommentLink").click(reportClickHandler);

 	//Style footer navigation correctly depending on guide
 	if( $('div#guide').length == 0 ) {
 		$('ul#footerNav').css('margin-top', '30px');
 	}

 	//disable voting when you've already voted
 	if( $('.updown-widget-voted a').hasClass('voted') || $('.updown-widget-voted a').hasClass('votingDisabled') ) {
 		$('.updown-widget-voted a').click( function() {
 			return false;
 		});
 	}


 	//add regularBox around failed comment validation screen
 	$('#addBox').parent().parent().parent().addClass('comments');
 	$('#addBox').parent().parent().wrap('<div class="box"></div>');
 	var regularBox = $('#addBox').parent().parent().parent().parent().parent();
 	var contentBox = $('#addBox').parent().parent().parent();
 	regularBox.find('h2').prependTo(contentBox);

 	if( $('div.comments').length ){
 		$('div.comments').each( function() {
 			var i=0;
 			$(this).parents().each( function() {
	 			if( $(this).hasClass('regularBox')){
	 				i++;
	 			}
 			});
 			if(i==0) {
	 			$('div.comments').each( function(){
	 				if( $(this).parent().hasClass('videoComments')){
						//do nothing
	 				}
	 				else{
	 					$(this).wrap('<div class="regularBox"></div>');
	 					$(this).parent().prepend('<div class="bozTop"></div>');
	 					$(this).parent().append('<div class="bozBottom"></div>');
	 					$(this).addClass('contentBox');
	 				}
	 			});
	 		}
 		});
 	}


 	//video expire soon time remaining
 	$('.doTimeCheck', $('.videoCarouselDesc')).each( function() {
 		$(this).text(nettiTimeLeft($(this).text()));
 		$(this).show();
 	});
 	 	
 	
	//Creat target _blank for anhcors with rel=external and class=external
	$('a.external').each( function(){
		if( $(this).attr('rel') == 'external' ){
			$(this).attr('target', '_blank');
		}
	});


 	//comment width on blog entry
 	if( $('.blogSingle').length ){
 		var comments = $('.blogSingle').parent().next();

 		$(comments).find('.commentBox').each( function(){
 			$(this).addClass('commentBoxExtended');
 		});
 	}

 	//pad weather unit/netti tv browser with tabs/user profile
 	$('#weatherTabsHolder').parent().parent().parent().parent().css('margin-top', '30px');
 	$('#userContent').parent().parent().css('margin-top', '30px');

 	//set padding on program guide page
 	$('#fullProgramGuide').parent().css('padding', '0px');
 	$('#fullProgramGuide').parent().css('width', '992px');

	//set position of custom background images depending on header ad
	if($('#topBannerHolder .ad').length > 0) {
		if($('#topBannerHolder .ad').height() > 0 ){
			var setHeight = $('#topBannerHolder .ad').height();
			//assumes max height of banner ad is 200px
			setHeight = -200 + setHeight + 30;
			setHeightIE = setHeight+'px';
			setHeight = '50% '+setHeight+'px';
			if($.browser.msie) {
				$('body').css('background-position-x', '50%');
				$('body').css('background-position-y', setHeightIE);
			}
			else{
				$('body').css('background-position', setHeight);
			}
		}
	}

	$('body').addClass('custom');

	//position ads on right side of video player
	if( $('.videoPlayerArea').length ){
		var adsCol = $('.videoPlayerArea').parent().next();

		var arrayOfClasses = $(adsCol).attr('class');
		if(arrayOfClasses) {
			arrayOfClasses = arrayOfClasses.split(' ');
		}
		else {
			arrayOfClasses = new Array();
		}

		adsCol = arrayOfClasses[0];
		var adCount = 0;

		$("."+adsCol+' > *').each( function(){
			if( $(this).hasClass('ad') ){
				adCount++;
			}
		});

		if(adCount >= 3){
			$('.videoPlayerArea').parent().next().css('padding-top', '10px');
		}
	}

	//show comment list for current video
	$('#videoComments').next().hide();

	// expand comment list if expandCookie for current comment block is set
	$('#contentWrap').find('#expandComments').each( function() {
		var expandCookieName = $(this).attr('class').split(' ').slice(0,1);

		if( $.cookie(expandCookieName[0]) ) {
			$(this).parent().parent().parent().next().show();
			$(this).removeClass('show');
			$(this).addClass('hide');
		}
	});

	$('#expandComments').click( function() {
		if( $(this).hasClass('show') ){

			// set expandCookie for current comment block
			expandCookieName = $(this).attr('class').split(' ').slice(0,1);
 			$.cookie(expandCookieName, 'true', { path: '/', expires: 0});

 			// show comments
			$(this).parent().parent().parent().next().show();
			$(this).removeClass('show');
			$(this).addClass('hide');
		}
		else{
			// unset expandCookie for current comment block
			expandCookieName = $(this).attr('class').split(' ').slice(0,1);
 			$.cookie(expandCookieName, null, { path: '/', expires: 0});

 			// hide comments
			$(this).parent().parent().parent().next().hide();
			$(this).removeClass('hide');
			$(this).addClass('show');
		}

		return false;
	});

	$('#expandCommentsRuutu').click( function() {
		if( $(this).hasClass('show') ){
			$('.videoComments', $(this).parent().parent().parent().parent()).show();
			$(this).removeClass('show');
			$(this).addClass('hide');
		}
		else{
			$('.videoComments', $(this).parent().parent().parent().parent()).hide();
			$(this).removeClass('hide');
			$(this).addClass('show');
		}

		return false;
	});
	
	//Mini video carousel (normal player)
	if( $('#nettiTvBrowserMiniPromo').length ) {
		//Register clicks on tabs
		$('.videoTabNavigation li a').click( function(){
			//Show the correct carousel
			var tabToShow = (this.hash).substr(1);
			$('div.tabVideo', $('#nettiTvBrowserMiniPromo') ).each ( function(){
				$(this).hide();
			});
			$('#'+tabToShow).show();
			
			//Set correct carousel nav
			$('div', $('#nettiTvBrowserMiniPromo #videoNavWrapper') ).each ( function(){
				if($(this).attr('id') == 'nav-'+tabToShow){
					$(this).show();
				}
				else{
					$(this).hide();
				}
			});
			//Menu highlight
			$('.videoTabNavigation li a').removeClass('activeTabNav');
			$(this).addClass('activeTabNav');
			
			return false;
		});
	}
	
	//Mini radio carousel (radio player)
	if( $('#nettiTvBrowserMiniPromo').length ) {
		//Register clicks on tabs
		$('.radioTabNavigation li a').click( function(){
			//Show the correct carousel
			var tabToShow = (this.hash).substr(1);
			$('div.tabMediaType', $('#nettiTvBrowserMiniPromo') ).each ( function(){
				$(this).hide();
			});
			$('#'+tabToShow).show();
			
			if($('#'+tabToShow).attr("id") == 'podcasts'){
				$('#preLatestDescPod').trigger('click');
			}
			else{
				$('#preLatestDesc').trigger('click');
			}	
			
			//Menu highlight
			$('.radioTabNavigation li a').removeClass('activeTabNav');
			$(this).addClass('activeTabNav');
			
			return false;
		});
	}
		
	//add some separation to last comment box and comment form
	$('.commentBox:last').css('margin-bottom', '20px');


	//program matrix
	if( $('#programMatrix').length ){

		if( $('#programMatrix .contentTabs').length ){
			$('#programMatrix').addClass('tabVisible');
		}

		//program matrix tabs
		$('#programMatrix ul.nettiTabNav li a').click( function(){

			$('#programMatrix ul.nettiTabNav li a').each( function(){
				$(this).removeClass('activeTabNav');
			});

			$(this).addClass('activeTabNav');
			
			// Show link to movies in datetime order only on Nelonen.fi
			if($(this).find('span').html() == 'Elokuvat') {
				$('.matrixMoviesLink').show();
			}
			else {
				$('.matrixMoviesLink').hide();			
			}

			//remove all breaks, hide error message
			$('#thumbContainer br').remove();
			$('#noPrograms').hide();

			//get filter
			currentFilter = $(this).attr('id');
			var currentFilters = new Array();
			currentFilters = currentFilter.split('-');

			var shown = 0;

			$('.thumbBox').hide();
			if( currentFilter == 'filterAll' ){
				$('.thumbBox').show();
			}
			else {
				for(var i=0; i<currentFilters.length; i++){
					$('.thumbBox.'+currentFilters[i]).show();
				}					
			}
			shown = $('.thumbBox.visibleThumbBox').length;

			//break after every 8 to maintain row heights
			if( shown > 0 ){
				var i =0;
				$('.thumbBox:visible').each(function(){
					i++;
					if(i==8) {
						$(this).after('<br style="clear:left;" />');
						i=0;
					}
				});

			}
			else{
				//inform people there is nothing to see
				$('#noPrograms').html('Ei ohjelmia.');
				$('#noPrograms').show();
			}
		});
	}
	
	//switch tab based on GET['tab_id']
	//two cases, normal matrix and LIV matrix
	//these are hardcoded in node-mu_matrix.tpl
	//Note any changes to the matrix template tab must be reflected here
	if (typeof showProgramMatrixTabId!=='undefined' && typeof showProgramMatrixLIV!=='undefined'){
		if (showProgramMatrixTabId!==false){
			//if LIV matrix, handle differently
			if (showProgramMatrixLIV!==1){
				//console.log('switch normal');
				if (showProgramMatrixTabId==4 || showProgramMatrixTabId==5){
					$('#programMatrix ul.nettiTabNav li a#filter4-filter5').trigger('click');
				}
				else{
					$('#programMatrix ul.nettiTabNav li a#filter'+showProgramMatrixTabId).trigger('click');
				}
			}
			else{
				//console.log('switch LIV tab');
				//LIV
				if (showProgramMatrixTabId==6){
					$('#programMatrix ul.nettiTabNav li a#filter6').trigger('click');
				}
				else{
					$('#programMatrix ul.nettiTabNav li a#filter'+showProgramMatrixTabId).trigger('click');
				}
			}
		}
	}
	
	//Hover on ruutu related carousel
	if( $('a.imgLink', $('.carouselVideoBoxHolder')).length ){
		//tooltip settings
		$('ul .imgLink', $('.carouselVideoBoxHolder')).tooltip({track: true,delay: 0,showURL: false,fixPNG: true,showBody: " ---- ",extraClass: "pretty fancy",top: 10,left: 10});
	}

	// Search v2	
	// The search handler
	$('.searchBox2 form fieldset input').bind("keyup", {jqel:$('.searchBox2 form fieldset input')}, handleSearch);
	
	// Clear the box on focus
	$('.searchBox2 form fieldset input').bind("focus", {}, function(){$('.searchBox2 form fieldset input').val('');});

	// Hide the results when user clicks anywhere...
	$('html').click(function() {
		$('#searchTipHolder2').hide();
	});
	// .. except the results themselves
	$('#searchTipHolder2').click(function(event){
		event.stopPropagation();
	});
	// done with search

	if( $('.extendedScroll').length ){
		$('.extendedScroll').each( function(){
			$(this).next().css( 'height', $(this).height() );
			$(this).next().find('.featuredPostBox').each( function() {
				$(this).css('width', '285px');
			});
			$(this).next().jScrollPane({scrollbarWidth: 14, scrollbarMargin: 0, dragMinHeight: 40, dragMaxHeight: 40, showArrows: true});
			$(this).next().find('.jScrollPaneTrack').css('background-color', '#eeeeee');
		});
	}
	
	
	//mu_text_small_image comments
	$('.commentLink a').click( function(){
		if( $(this).hasClass('show') ){
			$(this).parent().parent().next().hide();
			$(this).removeClass('show');
		}
		else{
			$(this).parent().parent().next().show();
			$(this).addClass('show');
		}
		
		return false;
	});
	
	//Radio player open new window
	$('.openNewWindow a').click( function() {
		var parts = $(this).attr('id').split(',');
		window.open(parts[0], "", "height="+parts[2]+",width="+parts[1]+",modal=yes,alwaysRaised=yes")
		return false;
	});
	
	//Video player embed code pop up
	$('.videoEmbedCodeContainer a').click( function() {
		var value = '';
		if( $(this).hasClass('ruutu') ){
			var position = $(this).parent().parent().parent().position();
			value = position.top + 200;
		}
		else{
			position = $(this).parent().parent().parent().parent().position();
			value = position.top - 100;
		}
		$('.videoEmbedCode').css('top', value);
	});

	//Comment promo box expand 
	$('.expandLongComment').click(function(){
		$('.snippetC').toggle();
		$('.originalC').toggle();
		
		return false
	});
	
	//Pad sub nav if there are so many items that breaks one line
	if( $('#subNav').length ){
		var listWidth = 0;
		$('#subNav li').each( function() {
			listWidth = listWidth + $(this).width();
		});
		if( listWidth > 954 ){
			$('#subNav li').css('padding-bottom', '15px');
		}
	}
	
	// Count system notifications
	if(isAuthenticated==1) {
		$.get(drupalUrl+'ajax/get_system_notification_count', function(data) {
			if(data != 0) {
				$('a#loggedStatus').append(' <b style="background:red;color:white;">&nbsp;'+data+'&nbsp;</b>');			
			}
		});	
	}
	

	refreshCompetition();
	nelonenRoundedCorners();
	refreshRockEventsButtons();
});  // end document.ready?

function trimTeaser(teaser){
	if( teaser.length > 50 ){
		teaser = teaser.substr(0,60);
		teaser += '...';
	}

	return teaser;
}

//Hide/Show clip/episode titles and messages
function titleCheck(action, override) {
	
	//We are showing clips from a series on the override list so we need to also show the message about episodes
	if(override){
		$('#video_episode_title').show();
		$('#video_episodes').html('<p>Tämän sarjan jaksoja ei ole nähtävillä verkossa, sillä sarjalle ei ole verkkoesitysoikeuksia.</p>');
		$('#video_episodes').show();
		$('#video_clip_title').show();
		$('#video_clips').show();
	}
	else{
		if( !( $('#video_clips').text() == 'Ei klippejä.' && $('#video_episodes').text() == 'Ei jaksoja.') ){
			$('#video_episode_title').show();
			$('#video_clip_title').show();
			$('#video_episodes').show();
			$('#video_clips').show();
	
			if( $('#video_clips').text() == 'Ei klippejä.' ){
				$('#video_clip_title').hide();
				$('#video_episode_title').hide();
				$('#video_clips').hide();
			}
			if( $('#video_episodes').text() == 'Ei jaksoja.' ){
				$('#video_episode_title').hide();
				$('#video_clip_title').hide();
				$('#video_episodes').hide();
			}
		}
		else{
			$('#video_episode_title').show();
			$('#video_clip_title').show();
			$('#video_episodes').show();
			$('#video_clips').show();
		}
	}
}

function nettiTimeLeft(date) {
	//calculate remaining time left for video on netti tv
	var parts = date.split(' ');
	var dateParts = parts[0].split('-');
	var timeParts = parts[1].split(':');
	dateParts[1] = dateParts[1] - 1;

	var expires = new Date(dateParts[0],dateParts[1],dateParts[2],timeParts[0],timeParts[1],timeParts[2]);
	var today = new Date();
	var day = 1000*60*60*24;
	var hour = 1000*60*60;
	var min = 1000*60;

	var diffTime = 0;

	//exception for unlimited videos
	if (date == '0000-00-00 00:00:00') {
		diffTime = '';
	}
	//is the time less than 1 day
	else if( (expires.getTime() - today.getTime()) / day < 1 ){
		//is the time less than 1 hour
		if( (expires.getTime() - today.getTime()) / hour < 1 ){
			//less than 1hr so calulate minutes
			diffTime = Math.round((expires.getTime() - today.getTime()) / min);
			//minute or minutes
			if( diffTime > 1 ){
				diffTime += ' minuuttia jäljellä';
				}
 			else{
				diffTime = '1 minuutti jäljellä';
			}
		}
		else{
			//calculate remaining hours
			diffTime = Math.round((expires.getTime() - today.getTime()) / hour);
			//hour or hours
			if( diffTime > 1 ){
				diffTime += ' tuntia jäljellä';
			}
			else{
				diffTime = '1 tunti jäljellä';
			}
		}
	}
	else{
		//calculate remaining days
		diffTime = Math.round( (expires.getTime() - today.getTime()) / day );
		if( diffTime > 5 ){
			//dont show time greater than 5 days
			diffTime = '';
		}
		else{
			if( diffTime > 1 ){
				diffTime += ' päivää jäljellä';
			}
			else{
				diffTime = '1 päivä jäljellä';
			}
		}
	}

	return diffTime;
}

function nettiDateOrder(date) {
	//order the date stamp correctly
	var parts = date.split(' ');
	var dateParts = parts[0].split('-');
	var timeParts = parts[1].split(':');

	var realDate = dateParts[2]+'.'+dateParts[1]+'.'+dateParts[0]+' '+timeParts[0]+':'+timeParts[1];

	return realDate;
}

function decode(encodedUrl) {
	//needed to decode headings from cookie which are encoded
	return decodeURIComponent(encodedUrl.replace(/\+/g,  " "));
}


function setAutoGrow() {
	//making the comment textarea function as req
	$('textarea').each(function(){
		if($(this).hasClass('addAutoGrow')){
			$(this).attr('rows','1');
			$(this).attr('cols','10');
			$(this).autogrow({
				maxHeight: 507
			});
			//$(this).val('Kirjoita tähän kommenttisi');
		}
	});
}

function reportClickHandler() {
 	var location = $(this).attr("href");
 	var thisElem = $(this);
 	$.get(location, function(data) {
 		thisElem.html(data);
 	});

 	return false;
 }

function mandatoryFields(obj, re) {
 	var fieldMissed = false;

 	if(re){
 		//check text fields
	 	$("#"+$(obj).attr('id')+' input:text').each( function() {
	 		if($(this).hasClass('mandatory')) {
	 			if($(this).val().length == 0){
		 			$(this).parent().prev().append("<em style='color:red'>&nbsp;Pakollinen tieto</em>");
		 			fieldMissed = true;
		 		}
	 		}
	 	});
	 	//check text area
	 	$("#"+$(obj).attr('id')+' textarea').each( function() {
	 		if($(this).hasClass('mandatory')) {
	 			if($(this).val().length == 0){
		 			$(this).parent().prev().append("<em style='color:red'>&nbsp;Pakollinen tieto</em>");
		 			fieldMissed = true;
		 		}
	 		}
	 	});
	 	//selects
		$("#"+$(obj).attr('id')+' select').each( function() {

	 		if($(this).hasClass('mandatory')) {
	 			if($(this)[0].selectedIndex == 0){
		 			$(this).parent().prev().append("<em style='color:red'>&nbsp;Pakollinen tieto</em>");
		 			fieldMissed = true;
		 		}
	 		}
	 	});

	 	//checkboxes
		$("#"+$(obj).attr('id')+' .former-checkbox-set').each( function() {
			var checkCount = 0;
			var noChecks = 0;

			$("#"+$(obj).attr('id')+' .former-checkbox').each( function() {
				noChecks++;
				if($('input', $(this) ).attr('checked') == false && $(this).hasClass('mandatory')){
					checkCount++;
				}
			});

			if(noChecks == checkCount) {
				$($(this).parent().prev()).append("<em style='color: red'>&nbsp;Pakollinen tieto</em>");
				fieldMissed = true;
			}
		});

	 	// Single checkbox with "required" class - TOS, for example
		$("#"+$(obj).attr('id')+' .former-simple-checkbox').each( function() {
			if($('input', $(this) ).attr('checked') == false && $(this).hasClass('mandatory')){
				$(this).append("<em style='color: red'>&nbsp;Pakollinen tieto</em>");
				fieldMissed = true;
			}
		});

 	}
 	else {
	 	//check text fields
	 	$("#"+$(obj).attr('id')+' input:text').each( function() {
	 		if($(this).hasClass('mandatory')) {
	 			if($(this).val().length == 0){
		 			$("#"+$(this).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Pakollinen tieto</em>");
		 			fieldMissed = true;
		 		}
	 		}
			if($(this).hasClass('email')) {
				prgC = checkEmail($(this).val());

				if(!(prgC)){
					$("#"+$(this).parent().attr("id")+" label").append("<em style='color:red'>&nbsp;Epäkelpo sähköpostiosoite</em>");
					fieldMissed = true;
				}
			}

	 	});
	 	//check text area
	 	$("#"+$(obj).attr('id')+' textarea').each( function() {
	 		if($(this).hasClass('mandatory')) {
	 			if($(this).val().length == 0){
		 			$("#"+$(this).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Pakollinen tieto</em>");
		 			fieldMissed = true;
		 		}
	 		}
	 	});
	 	/* Mandatory multiple checkboxes makes no sense, and this code blocks makes even less.
	 	Until a single checkbox is created with a check box set... */
	 	//checkboxes
		$("#"+$(obj).attr('id')+' div .form-checkboxes').each( function() {
			var checkCount = 0;

			$(this).find('input:checkbox').each( function() {
				if($(this).attr('checked') == true){
					checkCount++;
				}
			});

			if(checkCount < 1) {
				$(this).append("<em style='color: red'>&nbsp;Pakollinen tieto</em>");
				fieldMissed = true;
			}
		});
		

	 	// Single checkbox with "required" class - TOS, for example
		$("#"+$(obj).attr('id')+' div .form-checkbox').each( function() {
			if($(this).attr('checked') == false && $(this).hasClass('required')){
				$(this).parent().append("<em style='color: red'>&nbsp;Pakollinen tieto</em>");
				fieldMissed = true;
			}
		});

		//selects
		$("#"+$(obj).attr('id')+' select').each( function() {

	 		if($(this).hasClass('mandatory')) {
	 			if($(this)[0].selectedIndex == 0){
		 			$("#"+$(this).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Pakollinen tieto</em>");
		 			fieldMissed = true;
		 		}
	 		}
	 	});
	 
	 	// files
	 	$("#"+$(obj).attr('id')+' input:file').each( function() {
			if($(this).val() == '' && $(this).hasClass('mandatory')) {
				fieldMissed = true;
	 			$(this).parent().prepend("<em style='color:red'>&nbsp;Pakollinen tieto</em>");
			}
		});
	 }

 	return fieldMissed;
}

function checkMaxVal(value, obj, re) {
 	var maxVal = value.substr(6,value.length);
 	var max = parseInt(maxVal, 10);
 	
 	var result = onlyNumbers($(obj).val());

 	if(result){
 		var user = parseInt($(obj).val());

 		if(user > max) {
 			if(re) {
 				$(obj).parent().prev().append("<em style='color:red'>&nbsp;Arvo on liian suuri</em>");
 			}
 			else {
 				$("#"+$(obj).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Arvo on liian suuri</em>");
 			}
 			return false;
 		}
 		else {
 			return true;
 		}
 	}
 	else {
 		if(re){
 			var location = $(obj).parent().prev();
 			$(location).find('em:first').html('&nbsp;Syötä numero');
 		}
 		else{
	 		if($("#"+$(obj).parent().attr("id")+" label").length == 0){
	 			$("#"+$(obj).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Syötä numero</em>");
	 		}
	 	}
 		return false;
 	}

 }

function checkMinVal(value, obj, re) {
 	var minVal = value.substr(6,value.length);
 	var min = parseInt(minVal, 10);

 	var result = onlyNumbers($(obj).val());

 	if(result){
 		var user = parseInt($(obj).val(), 10);

 		if(user < min) {
 			if(re){
 				$(obj).parent().prev().append("<em style='color:red'>&nbsp;Arvo on liian pieni</em>");
 			}
 			else{
 				$("#"+$(obj).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Arvo on liian pieni</em>");
 			}
 			return false;
 		}
 		else {
 			return true;
 		}
 	}
 	else {
 		if(re){
 			$(obj).parent().prev().append("<em style='color:red'>&nbsp;Syötä numero</em>");
 		}
 		else{
 			$("#"+$(obj).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Syötä numero</em>");
 		}
 		return false;
 	}

 }


function checkMaxLength(value, obj, re) {
	var maxLength = value.substr(9,value.length);
	var length = parseInt(maxLength, 10);

 	if ( $(obj).val().length > length){
 		if(re){
 			$(obj).parent().prev().append("<em style='color:red'>&nbsp;Arvo on liian pitkä</em");
 		}
 		else{
 			$("#"+$(obj).parent().attr("id")+" label").append("<em style='color: red'>&nbsp;Arvo on liian pitkä</em>");
 		}

 		return false;
 	}
 	else {
 		return true;
 	}
}

function onlyNumbers(value) {
	var check = /^[0-9]*$/;
	if (value.match(check)) {
		return true;
	} else {
		return false;
	}
}


function checkEmail(inputvalue){
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(pattern.test(inputvalue)){
		return true;
    }else{
		return false;
    }
}


function ratingEngineSubmissionFrmSubmit() {
	//emtpy error labels
	$("#itemSubmissionFrm em").empty();

 	//check mandatory fields contain value
	var result = mandatoryFields($('#itemSubmissionFrm'), true);

	if(!result){
 		var prgA = true;
 		var prgB = true;
 		var prgC = true;
 		var prgD = true;

		//get each input and check classes (text)
		$('#itemSubmissionFrm input:text').each( function() {
			var arrayOfClasses = $(this).attr('class').split(' ');

			for(var i=0; i<arrayOfClasses.length; i++) {
				if(arrayOfClasses[i] == 'maxval' ) {
					prgA = checkMaxVal(arrayOfClasses[i+1], $(this), true);
				}
				if(arrayOfClasses[i] == 'minval' ) {
					prgB = checkMinVal(arrayOfClasses[i+1], $(this), true);
				}
				if(arrayOfClasses[i] == 'email' ) {
					prgC = checkEmail($(this).val());
					if(!(prgC)){
						$(this).parent().prev().append("<em style='color:red'>&nbsp;Epäkelpo sähköpostiosoite</em>");
					}
				}
			}
		});

		//get each textarea and check classes
 		$('#itemSubmissionFrm textarea').each( function() {
 			var arrayOfClasses = $(this).attr('class').split(' ');

			for(var i=0; i<arrayOfClasses.length; i++) {
				if(arrayOfClasses[i] == 'maxlength' ) {
					prgD = checkMaxLength(arrayOfClasses[i+1], $(this), true);
				}
			}

 		});
		
 		if(!prgA || !prgB || !prgC || !prgD){
 			return false;
 		}
 		else{
 			mySubmit('itemSubmissionFrm');
 		}

	}
	else{
		return false;
	}

}


function setClickHandlers() {
	if (typeof Drupal.behaviors.voteUpDown == "function") {
		Drupal.behaviors.voteUpDown(); //This sets comment rating click handlers
	}

	//Report inappropriate comments
	$(".reportCommentLink").click(reportClickHandler);
}

/**
 * Using this keeps the user from posting the form by pressing enter in a text field
 *
 */

function mySubmit(formId) {
	window.maySubmit = true;
	$('#'+formId).submit();
}


$(function () {
    var tabContainers = $('div.tab');

    // Allows setting of initially active tab, or not if you don't want to.
    if($('ul.tabNavigation .initiallyActiveTab').length > 0) {
    	var filter = '.initiallyActiveTab';
    }
    else {
    	var filter = ':first';
    }

    $('ul.tabNavigation a').click(function () {

        tabContainers.hide().filter(this.hash).show();
        $('ul.tabNavigation a').removeClass('activeTabNav');
        $(this).addClass('activeTabNav');
        return false;

    }).filter(filter).click();
});




//addThis variables
var addthis_pub = "nelonen";
var addthis_brand = "Nelonen";
var addthis_header_color = "#ffffff";
var addthis_header_background = "#1c7ac4";
var addthis_language = "fi";
var addthis_offset_left = -80;
var addthis_options = 'digg, myspace, facebook, twitter, favorites, delicious, google, live, linkedin, myspace, slashdot';


/**
 * Fetches a new version of the comment form(with CAPTCHA) for anonymous users
 *
 */

function get_comment_form() {
	// This helps to redirect the user back to the place where user commented from
	if(window.location.href.indexOf('?') != -1) {
		var getParams = window.location.href.slice((window.location.href.indexOf('?'))+1);
	}
	else {
		var getParams = '';
	}

	// Anonymous users need more things on the comment form. Make sure we didn't already submit
	// by checking for the ffa field.
	// disable the submit dummy button
	// only enable it when after ajax done
	$('#submit-dummy').attr("disabled", true);
	if($('#edit-fetch-comment-form').length > 0) {
		var commentElems = $("div.comments form");
		
		// These are used to check for the type of item we're commenting on
		var commentContainers = $("div.comments");
		var i = 0;
		
		commentElems.each( function() {
			var commentElem = $(this);
			commentElem.find("*").focus(function() {
				// Get actual comment form when the dummy form is focused
				
				// Check if we're commenting on a randomly selected video
				var commentContainer = commentContainers.eq(i);
				if(commentContainer.parent().hasClass('videoComments') && getParams=='') {
					// Edit getParams to set corrent return address for the comment redirection
					getParams = 'vt='+videoBrowser_vt+'&vid='+videoBrowser_vid;
				}
				
				//store focused element id so that we can restore focus when the form has been re-rendered
				var focusedId = $(this).attr("id");

				var nidBeingCommented = commentElem.find('.nid-being-commented').val();

				$.get(drupalUrl+"render_comment_form/"+nidBeingCommented+"/"+currentNid+"/"+commentElem.attr('id')+"/"+encodeURIComponent(getParams), function(output) {
					var currentContent = $("#"+focusedId).val();

					var submitDummy = commentElem.find('.submit-dummy');

					commentElem.parent().parent().replaceWith(output);
					//enable submit dummy
					submitDummy.removeAttr("disabled");
					setAutoGrow();

					//For improved user experience
					$("#"+focusedId).val(currentContent);
					$("#"+focusedId).focus();

					$('fieldset.captcha').css('float', 'left');
					//$('fieldset.captcha').css('width', '325px');
					$('fieldset.captcha').css('margin', '0');
					$('fieldset.captcha').css('margin-left', '10px');
					$('fieldset.captcha').after($('#submit-dummy'));
					submitDummy.css('margin-top', '194px');
					submitDummy.css('margin-left', '25px');

				});	// end get
			});	// end focus
		});	// end each
	}
	else{
		//re-enable the submit dummy
		$('#submit-dummy').removeAttr("disabled");
	}
}

//Carousels
$(function()
{
	$('.mini-video-carousel').jScrollPane({scrollbarWidth: 14, scrollbarMargin: 0, dragMinHeight: 40, dragMaxHeight: 40, showArrows: true});
});


$(function() {
	//Looped video carousel
	//Iframe carousel
	//Article carousel
	//Video carousels
	
	$('.video-carousellite-looped').each( function() {
		var controls = $('input', $(this)).attr('value');
		controls = controls.split(',');
		$(this).jCarouselLite({
	        btnNext: controls[0],
	        btnPrev: controls[1],
	        start: 0,
	        visible: 4
	    });
	    
	    //Show part of the next item
	    $(this).css('width', '970px');
	    if( $(this).hasClass('carouselBoxHolder') ){
	    	$(this).css('width', '960px');
	    }
	});
	
	$('.video-carousellite-looped-external').each( function() {
		var controls = $('input', $(this)).attr('value');
		controls = controls.split(',');
		$(this).jCarouselLite({
	        btnNext: controls[0],
	        btnPrev: controls[1],
	        start: 0,
	        visible: 4
	    });
	    
	    //Make smaller for external use
	    if( $(this).hasClass('carouselBoxHolder') ){
	    	$(this).css('width', '955px');
	    }
	});
	
	//Ruutu video promote
	$(".ruutu-video-promote-looped").each( function() {
		var noItems = $(".ruutu-video-promote-looped ul li").length;
		if( noItems == 0 ){
			$('.videoPromoteStepper').hide();
		}
	
		var controls = $('input', $(this)).attr('value');
		controls = controls.split(',');
		$(this).jCarouselLite({
	        btnNext: controls[0],
		    btnPrev: controls[1],
			visible: 1,
			start: 0,
			pauseOnHover: true,
			circular: true,
			auto: 5000,
			speed: 0,
			btnGo:
			    [".videoPromoteStepper #s0",
			    ".videoPromoteStepper #s1",
			    ".videoPromoteStepper #s2",
			    ".videoPromoteStepper #s3",
			    ".videoPromoteStepper #s4",
			    ".videoPromoteStepper #s5",
			    ".videoPromoteStepper #s6",
			    ".videoPromoteStepper #s7",
			    ".videoPromoteStepper #s8"],
			beforeStart: function(a) {
				$(a).parent().fadeTo(300, 0);
				$('.videoPromoteStepper a').each( function() {
					if( $(this).hasClass('currentSelected') ) {
						$(this).removeClass('currentSelected');
					}
				});
			},
			afterEnd: function(a) {
				var curId = $(a).attr('id').substr(1);
				$('.videoPromoteStepper #s'+curId).addClass('currentSelected');
				$(a).parent().fadeTo(300, 1);
			}
		});
		
		$(this).css('visibility', 'visible');
		$(this).css('left', 'auto');
	});
	
	//Trigger click to position the hidden elements properly (mini video browser)
	$('#preLatestDesc').trigger('click');
	$('#preradioTrigger').trigger('click');
	
});


//Footer program guide window
$(function() {
	$('.programInfoWindow').each( function() {

		$(this).click( function() {
			//Load the content into window
			$('.programInfoWrapper').html('');
			$('.programInfo .programInfoWrapper').html($(this).parent().next().html());
			
			//Width
			var width =  $('.programInfo').width() / 2 - ($(this).width() / 2);
			
			//offset of the initial link
			var offset = $(this).offset();
				
			// Fetch the programme detail for the programme being viewed
			var xmlid = $('.programInfo .programme_xmlid').html();
			var elThumb = $('.programInfo img.programInfoLogo');
			
			var elInfoDetail = $('.programInfo .programInfoDetails');
			
			var elClose = '<p><a class="close" href="#">Sulje</a></p>';
			
			//get program detail
			$.get(base_url+"/ajax/nelonen_m4_fetch_footer_programme_detail/"+xmlid, function(data) {
				if(data) {
					data = eval("("+data+")");
					//thumbnail
					if (data['thumbnail_path']){
						elThumb.attr('src', static_base_url+'/'+data['thumbnail_path']);
					}
						
					//name
					var elName = '<h5 class="programInfoName">' + data['channel_name'] + ': ' +data['name'] + '</h5>';

					//description header
					if (data['watch_video_link']!=null){
						var elDescHeader = '<p class="programInfoDate">'
											+ data['description_header']
											+ '<br />'
											+ data['watch_video_link']
											+ '</p>';
					}
					else{
						var elDescHeader = '<p class="programInfoDate">'
											+ data['description_header']
											+ '</p>';
					}

					//description
					var elDesc = '<div class="programInfoDescription">' 
									+ data['description_text']
									+ '</div>';
					
					var infoDetailHTML = elName + elDescHeader + elDesc + elClose + elInfoDetail.html();
					elInfoDetail.html(infoDetailHTML);
					
					//Calculate size and show
					var height = $('.programInfo').height();
		
					//Vertical position
					if( height > offset.top ){
						$('.programInfo').css("top", offset.top + 10 );
						$('.programInfo .programInfoBottom').insertBefore($('.programInfo .programInfoWrapper'));
						$('.programInfo .programInfoWrapper').addClass('flipped');
						$('.programInfo .programInfoBottom').addClass('flipped');
					}
					else{
						$('.programInfo').css("top", offset.top - height);
					}
		
					//Horizontal position
					if((offset.left - width) > 0) {
						$('.programInfo').css("left", offset.left - width);
					} else {
						$('.programInfo').css("left", 0);
					}
		
					//Show the window
					$('.programInfo').show();		
					
					//Closing Window
					$('.programInfo .close').bind("click", function(){
						$('.programInfo').hide();
						$("html").unbind("click");
						return false;
				    });
				    
				    $(document).click(function() {
						$('.programInfo').hide();                                           
					});
					$('.programInfo').click(function(e) {
						e.stopPropagation();
					});
					
				}
			});

			return false;
		});
	});
});

function handleSearch(e) {
	offsets = $('#search2').offset();
	$('#searchTipHolder2').css({"top": offsets.top + 35, "left": offsets.left-150});
	
	var searchTermLength = $('#searchTerm').val().length; 
	var searchPrograms = {};
	var searchVideos = {};
	var searchAudio = {};
	var searchNews = {};
	var searchPages = {};
	//searchGroups['types'] = ["page", "video_episode", "video_clip", "news", "program_site", "audio"];
	searchPrograms['types'] = ["program_site"];
	searchVideos['types'] = ["video_episode", "video_clip"];
	searchAudio['types'] = ["audio"];
	searchNews['types'] = ["news"];
	searchPages['types'] = ["page"];
	
	searchPrograms['site'] = [searchSite];
	searchVideos['site'] = [searchSite];
	searchAudio['site'] = [searchSite];
	searchNews['site'] = [searchSite];
	searchPages['site'] = [searchSite];
	
	var params = {};
	params['search'] = e.data.jqel.val();
	params['groups'] = [searchPrograms, searchVideos, searchAudio, searchNews, searchPages];
	//params['site'] = searchSite;
	
	params = $.toJSON(params); // use jquery.json plugin
	
	if(searchTermLength >= 2) {
		$('#searchTipHolder2').show();
	
		//$.post(searchUrl, { site: searchSite, search: e.data.jqel.val() },
		$.post(searchUrl, { params: params },
		function(data){
				var results = eval('(' + data + ')');
				
				var resultCount = 0;
				var shouldUse = 2; //The amount of results one category should show
				var notUsed = 0; //The difference of the amount of result the category should have shown and it actually showed. The idea is to give unused "capacity" to the next category.
				
				var categories = new Array("programs", "videos", "audio", "news", "pages");
				$(".searchTipContent").html('');
				
				for (var i = 0; i < categories.length; i++) {
					var first = (resultCount == 0);
					var cat = categories[i];
					var catCap = cat.charAt(0).toUpperCase() + cat.substr(1); //"ucfirst"
					
					var tmp = showCategoryResults(results[i], '#result'+catCap+'2', cat, '#category'+catCap+'2', shouldUse + notUsed, first);
					resultCount += tmp;
					notUsed = ((i+1)*shouldUse) - tmp;
				}
				
			
				if (resultCount > 0) {
					$("#noHitsTitle2").hide();
					$("#noHits2").hide();
					$(".searchTipBox2:last").addClass("searchTipSeparator");
					
					$('#allresults').remove();
					$(".searchTipContent:last").after('<div id="allresults" class="searchTipBoxStyle"><a href="'+drupalUrl+'nelonen_search?searchkey='+e.data.jqel.attr("value")+'">N&auml;yt&auml; kaikki hakutulokset</a></div>');
				}
				else {
					$("#noHitsTitle2").show();
					$("#noHits2").show();
				}
			}
		);
	}
	else{
		$('#searchTipHolder2').hide();
	}
}


function showCategoryResults(resultSet, resultSelector, categoryName, categorySelector, maxAmount, first) {
	if (typeof resultSet == 'undefined' || resultSet.length == 0) {
		//No results in this category, hide the category header				
		$(categorySelector).hide();
		$(resultSelector).hide();
		return 0;
	}
	else {
		//Show search results
		$(categorySelector).show();
		$(resultSelector).show();
		
		if (first) {
			$(categorySelector).addClass("searchTipCategoryTop");
		}
		
		if (maxAmount > resultSet.length) {
			maxAmount = resultSet.length;
		}
		
		var categoryPaths = {'pages': 'node/', 'news': 'uutiset/', 'videos': 'node/', 'audio': 'media/', 'programs:': 'node/'}
		
		for (var i = 0; i < maxAmount; i++) {
			var divClass = "searchTipBoxStyle";
			
			if (i < (maxAmount - 1)) {
				divClass += " searchTipSeparator";
			}
			
			var html = '<div class="'+divClass+'">';
			
			var imgSrc = drupalUrl + defaultSearchIcon;
			if (typeof resultSet[i].thumbnailuri != 'undefined' && resultSet[i].thumbnailuri != null && resultSet[i].thumbnailuri != '') {
				imgSrc = resultSet[i].thumbnailuri;
			}
			
			html += '<img alt="" src="'+imgSrc+'"/>';
			
			if (resultSet[i].nodeurl) {
				var href = drupalUrl+resultSet[i].nodeurl;
			}
			else {
				//Fall back to default path
				var href = drupalUrl+categoryPaths[categoryName]+resultSet[i].nid;
			}
			
			html += '<p><a href="'+href+'" id="searchResultLink'+resultSet[i].id+'" class="searchResultLink">'+resultSet[i].title+"</a><br/>";
			
			if( resultSet[i].teaser.length > 100 ){
				teaser = resultSet[i].teaser.substr(0,100);
				teaser += '...';
			}
			else{
				teaser = resultSet[i].teaser;
			}
			
			html += teaser;
			
			html += "</p></div>";
			
			$(resultSelector).append(html);
		}
		
		//The search terms need to be reported
		$("a.searchResultLink").click(function() {
			var id = $(this).attr("id").substr("searchResultLink".length);
			var href = $(this).attr("href");
			var searchTerm = encodeURIComponent($("#searchTerm").val());
			$.post(drupalUrl+'_server/track_search', {searchTerm: searchTerm, searchId: id}, function() {
				window.location = href;	
			});
			return false;
		});
		
		return maxAmount;	
	}
}

function nelonenRoundedCorners() {
	$('.nelonenRoundedCorners').wrap('<div class="nelonenRoundedCornersWrapper"></div>');
	$('.nelonenRoundedCornersWrapper').append('<div class="nelonenRCTL"></div><div class="nelonenRCTR"></div><div class="nelonenRCBL"></div><div class="nelonenRCBR"></div>');
	$('.nelonenRoundedCornersWrapper').each(function() {
//		$(this).height($(this).find('img').height());
		$(this).width($(this).find('img').width());
	});
}

//Rock events competitions. Show the correct button for users based on participation status.
function refreshRockEventsButtons() {
	var isAuthenticated = $.cookie('isAuthenticated');
	
 	if(isAuthenticated == 1) {
		if ($(".rockEventsCompetition").length > 0) {
			console.log('longer');
			var rECStatus = $.cookie('rECStatus');
			
			if(rECStatus) {
				var rECStatusArray = rECStatus.split(',');
			}
			else {
				var rECStatusArray = new Array;			
			}
			
			$('.rockEventsCompetition').each(function() {
				// The id attribute holds the unique id of this competition
				var rECId = $(this).attr('id');
				rECId = rECId.substr(23);
				console.log('rECId: '+rECId);
				
				// If we find the id in the array, we show the "Cancel" button, and otherwise we show 
				// the "participate" button
				console.log(rECStatusArray);
				if(jQuery.inArray(rECId, rECStatusArray) == -1) {
					console.log('showing participate '+rECId);
					$('.rockEventsCompetitionParticipate'+rECId).show();
				}
				else {
					console.log('showing cancel '+rECId);
					$('.rockEventsCompetitionCancel'+rECId).show();
				}
			});
		}
	}
	// end rock events
}

function refreshCompetition() {
	$(".rockEventsCompetitionBody").hide();
	$(".rockEventsCompetitionHeader").click(function(){
		$(this).next(".rockEventsCompetitionBody").slideToggle(500);
		$(this).addClass("toggleOpen");
	});
}