/* Launch ArenaPlayer */
AreenaPlayerAPI.initialize();
var local_areena_init = false;


/* Cookie check for details vs. no-details in list view */
function areenaCheckCookie() {
    // Check cookie
    var areenatoggle = $.cookie('areenatoggle');
    // Set the user's selection to list view
    if (areenatoggle == 'details') {
        $('div.showlistitem').removeClass("no-details");
        $('a.showlisttoggle-large').addClass("strong");
        $('a.showlisttoggle-small').removeClass("strong");
    };
}

/* Check YLE Passi login based on cookie */
function checkYlePassiCookie() {
	var passiCookie = $.cookie('ChatYleFi');
	var baseUrl = 'https://login.yle.fi/login/';
	var lang = $("html").attr("lang");
	var logout_text = lang == 'fi' ? 'Kirjaudu ulos' : 'Logga ut';
	var login_text = lang == 'fi' ? 'Kirjaudu sisään' : 'Logga in';
	var uname_text = lang == 'fi' ? 'Kirjautunut' : 'Inloggad';
	var htmlContent = null;
	if (passiCookie != null && passiCookie.indexOf('user+loged+out') < 0) {
		var url = baseUrl + 'logout.php?url=' + location.href;
		var username = passiCookie.split('&')[0];
		htmlContent = "<ul class='passi logged-in'><li><a href='" + url + "'>" + logout_text + "</a></li><li class='userinfo'>" + uname_text + ": " + username + "</li></ul>";
	} else {
		var langId = lang == 'fi' ? '1' : '2';
		var url = baseUrl + 'index.php?language=' + langId + '&url=' + location.href.replace('http://', '');
		htmlContent = "<ul class='passi logged-in'><li><a href='" + url + "'>" + login_text + "</a></li></ul>";
	}
	$("#ylefi-account ul").length != 0 ? $("#ylefi-account ul").after(htmlContent) : $("#ylefi-account-login-wrapper").append(htmlContent);
}

/* function called on each pagination request (use history plugin) */
function areenaPaginationAnimated() {
	$("#paginator a").click(function () {
		window.location.hash = $(this).attr("href");
	    $.historyLoad( window.location.hash.replace(/^.*#/, '') ); // calls pageload
		return false;
	});
}


/* Hover toggle */
function areenaHoverToggle() {
    $("a.toggle-timeleft").mouseover(function() {
        $("p.showlistitem-timeleft").css({display:"none"});
        $(this).siblings('p').css({display:"block"});
    });
}


/* Clear hover */
function areenaHoverMouseOut() {   
    $("div.showlistitem-description").mouseover(function() {
        $("p.showlistitem-timeleft").css({display:"none"});
    });
    
    $("div.showlistitem-image > ul").mouseover(function() {
        $("p.showlistitem-timeleft").css({display:"none"});
    });    
            
    $("p.showlistitem-timeleft").mouseout(function() {
        $(this).css({display:"none"});
        $("p.showlistitem-timeleft").css({display:"none"});
    });  
}


/* Opens a standaloneplayer when clicked on netradio-index page */
function areenaNetradioOnClick(id, language) {
	    var selectedMenu = document.getElementById("radio_menu-"+id)
	    var chosenOption = selectedMenu.options[selectedMenu.selectedIndex]
	    if(language != "fi" && language!="sv") {
		    language = "fi"
	    }
	    if( chosenOption.value!="#" ) {
	    	   AreenaPlayerAPI.openStandalonePlayer('channel', chosenOption.value, language)
	    }
}


/* Initialize share form for ajax functionality */
function initShareForm() {
	var options = {
		target: '#shareform',
		success: function() {
			initShareForm();
		}
	};
    $('#relatedinfo-shareform').ajaxForm( options );
}


/* called after a jcarousel has been loaded */
function initCarousel( container ) {
	$(container).css('overflow', 'visible');
	$(container).fadeTo("slow", 1);
}


/* Begin Sitestat code */
function sitestat(ns_l) {
	ns_l += '&amp;ns__t=' + (new Date()).getTime();
    ns_0 = document.referrer;
    ns_0 = (ns_0.lastIndexOf('/') == ns_0.length-1) ? ns_0.substring(ns_0.lastIndexOf('/'), 0) : ns_0;
    if (ns_0.length > 0) {
        ns_l += '&amp;ns_referrer=' + escape(ns_0);
    }
    if (document.images) {
        ns_1 = new Image();
        ns_1.src = ns_l;
    } else {
        document.write('<img src="' + ns_l + '" width="1" height="1" alt="">');
    }
} // End Sitestat code


/* animates ongoing liveshows by displaying one show at a time in the livepuffbox */
function animateLives() {
	var liveElements = $("#livepuffbox p a");
	if ( liveElements.length <= 1)
		return;
	var animElement = $("#livepuffbox p #livescroller");
	animElement.animate({top: "-28px" }, 500, function() {
		$("#livepuffbox p a:first").insertAfter( $("#livepuffbox p a:last") );
		animElement.css("top", "0");
		setTimeout( 'animateLives()', 7000);
	});
}


/* function used by history plugin, takes care of viewing the right content in clip lists */
function pageload(hash) {
	/* do not animate on initial page load */
	if (!local_areena_init) {
		$("#animationhider").css("opacity", 0);
		$("#animationhider").css("height", $("#showlistcontent").height() - 44 + "px");
		$("#animationhider").css("width", $("#showlistcontent").width() + "px");
		$("#animationhider").fadeTo(350, 0.9, function() {
			$("div#ajaxloader").fadeIn(250);
			var loadurl = null;
			if (hash && ( hash.substring(0,1) == '/' || hash.substring(0,4) == 'http')) loadurl = hash;
			else if (!local_areena_init) loadurl = window.location.href.split('#')[0];
			// update cliplist content
			if (loadurl) {
				$("#showlistcontent").load(loadurl, null, function() {
					$("div#ajaxloader").fadeOut(0);
					$.scrollTo($('#showlist'));
				});
			}
		});
	}
	local_areena_init = false;
	return false;
}

function loadShareForm( url ) {
    $("#shareform").load(url, '', function() {
    	initShareForm();
    });
}


/* Launch Jquery */
$(document).ready( function() {
	$.ajaxSetup({ cache:true });
	local_areena_init = true;
	$.historyInit(pageload);
	checkYlePassiCookie();
	
    // Launch all js functions when jQuery is ready
    areenaCheckCookie();
    areenaPaginationAnimated();
    areenaHoverToggle();
    areenaHoverMouseOut();
    animateLives();

    // Refresh js functions when ajax is used
    $("#showlistcontent").ajaxComplete(function(request, settings){
    	areenaCheckCookie();
    	areenaPaginationAnimated();
    	areenaHoverToggle();
    	areenaHoverMouseOut();
    	$("#ajaxloader").fadeOut(0);
    	$("#animationhider").css("height", $(this).height() - 44 + "px");
    	$("#animationhider").fadeTo(500, 0, function() {
    		$("#animationhider").css("width", "0px");
    		$("#animationhider2").css("height", "0px");
    	});
    });
        
    /* Launch carousels */
    
    // other episodes carousel
    $('#carousel-episodes').jcarousel({
    	initCallback: function(carousel, state) { initCarousel('#wrap-episodes'); }
    });
    
    // related clips carousel
    $('#carousel-related').jcarousel({
    	initCallback: function(carousel, state) { initCarousel('#wrap-related'); }
    });
    
    // genre carousel 
    $('#carousel-genres').jcarousel({
    	initCallback: function(carousel, state) { initCarousel('#wrap-genres');}
    });
    
    // frontpage liftup webradio carousel
    $('#carousel-radio').jcarousel({
        scroll: 1,
        wrap: "both",
        animation: 100,
        initCallback: function(carousel, state) { initCarousel('#wrap-netradio'); }
    });
    
    // theme carousel
    $('#theme-related').jcarousel({
    	initCallback: function(carousel, state) { initCarousel('#wrap-theme');}
    });

    // details vs. no-details in list view
    $('.showlisttoggle a.showlisttoggle-small').click(function() {
      $('div.showlistitem').addClass("no-details");
      $(this).addClass("strong");
      $('.showlisttoggle a.showlisttoggle-large').removeClass("strong");
      // update cookie value
      $.cookie('areenatoggle', 'null', {path: '/'});
      return false;
    });

    $('.showlisttoggle a.showlisttoggle-large').click(function() {
      $('div.showlistitem').removeClass("no-details");
      $(this).addClass("strong");
      $('.showlisttoggle a.showlisttoggle-small').removeClass("strong");
      // update cookie value
      $.cookie('areenatoggle', 'details', {path: '/'});
      return false;
    });

    // Launch front page carousel with SWFobject 2.1 if 'cflow'-div exists
    if ($('#cflow').size() > 0) {
        var params = {};
        params.xml_url = $('#carousel-url').val();
        params.lang = $('#carousel-lang').val();
        var attributes = {};
        var flashvars = {}; 
        swfobject.embedSWF("flash/carousel-front.swf", "cflow", "920", "252", "9.0.15", flashvars, params, attributes);
    }

    // Ajax form handling for clip page
    initShareForm();

    // Social links
    $('#sociallinks').bookmark({compact: true,
    	sites: ['facebook', 'google', 'yahoo', 'delicious', 'digg', 'twitthis']
    });
    
    // Popup-windows with scrollbars
    var profiles = {scrollbars: {height:786, width:1024, scrollbars:1, toolbar: 1, status: 1, menubar: 1}}
    $(".popup").popupwindow(profiles);

});

