//se.no spesifikke greier.

// Login
var serviceId = "101";
var returnUrl = "http://www.se.no/";
var postLoginFunction = false;
var doRefresh = false;
var nextAlarm = "0";

var userId = "";
var parentFrontPage = "";

var mail1;
var mail2;
function writemail(mail1, mail2){
  document.open();
  document.writeln('<a href=mailto:' + mail1 + '@' + mail2 + '>');
  document.close();
}
function writesafemail(mail1, mail2){
  document.open();
  document.writeln(mail1 + '@' + mail2);
  document.close();
}


function initFront(){

	userId = $('div.loggedInUserId').attr("innerHTML");
	parentFrontPage = $('div#parentFrontPage').attr("innerHTML");	
	
	
	/* ------------------ FEATURED CONTENT --------------------- */
	
	var currentId = 1;
	
	$('div.promotop').oneTime(7000, "switchPromoContent", function() {switchToNext(); });
	
	$('.promoitem a').click(function() {
	
		var idArr = $(this).parent().attr("id").split('_');
		var id = parseInt(idArr[1]);
		switchTo(id);
		return false;
	});
	
	function switchTo(id) {
		
		id = parseInt(id);
		
		currentId = id;
		
		$('#curtain').css("z-index",301);
		$("#curtain").animate( { opacity:"1"}, 200, 'linear', function() {
			$(".titleshadow-left").css("opacity",0);
			$(".left-text").css("opacity",0);
			
			$('div.mainitem').addClass("invisible");
			$('div#promo_' + id).removeClass("invisible");
			
			$('div.promoitem').addClass("inactive");
			$('div#promothumb_' + id).removeClass("inactive");
			
			$("#curtain").animate( { opacity:"0" } , 200, 'linear', function() {
				$('#curtain').css("z-index",-1);
				$('div.promotop').stopTime("switchPromoContent");
				$("div#promo_" + currentId).oneTime(500, "showDescription", function() {
					//$("div#promo_" + currentId).children(".titleshadow-left").animate( { opacity:"1" } , 200);
					$(".titleshadow-left").animate( { opacity:"0.5" } , 200);
					$(".left-text").animate( { opacity:"1" } , 200);
				});
				
				$('div.promotop').oneTime(7000, "switchPromoContent", function() {switchToNext(); });
			});
			
			
			
		})
	}
	
	function switchToNext() {
		if (currentId < 4) {
			currentId = currentId + 1;
		}
		else {
			currentId = 1;
		}
		
		switchTo(currentId);
	}
	
	/* ------------------ EOF FEATURED CONTENT --------------------- */
	
	
	
	
	
	
	
	
	
	$('#myChannelsToggler').click(function(){
		toggleAlternatives();
		return false;
	});
	
	$('#myChannelsToggler2').click(function(){
		toggleAlternatives();
		return false;
	});
	
	$('#myChannelsToggler3').click(function(){
		window.scrollTo(0,0);
		toggleAlternatives();
		return false;
	});
	
	$('div.menu a.link-login').click(function(){
		displayLogin();
		return false;
	});	
	
	
	$('a#mainmenu-item-tvguide').hover(
	function(){
		$('#tvguide-alternatives').stopTime("hideHover");
		$('#tvguide-alternatives').css("display","block");
		return false;
	},
	function(){
		$('#tvguide-alternatives').oneTime(500, "hideHover", function() { $('#tvguide-alternatives').css("display","none"); });
		return false;
	});
	
	$('#tvguide-alternatives').hover(
	function(){
		$('#tvguide-alternatives').stopTime("hideHover");
		$('#tvguide-alternatives').css("display","block");
		return false;
	},
	function(){
		$('#tvguide-alternatives').oneTime(500, "hideHover", function() { $('#tvguide-alternatives').css("display","none"); });
		return false;
	});
	
	
	if (parentFrontPage != "ViewFavoritesReminders"){
		
		$("div#onTvNow").load("index.php5", {op: "OnTvNow"}, function(){
			initFavButtons("#onTvNow a.btn.favorite");	
		});
		
		$('div#onTvNow').everyTime(60000, "updateOnTvNow", function() {
			$("div#onTvNow").load("index.php5", {op: "OnTvNow"}, function(){
				initFavButtons("#onTvNow a.btn.favorite");	
			});
		});
	
		if (userId){
			
		
		//	$('div.favoritter-og-paminnelser').oneTime(1000, "initUserFavs", function() {
				$("div.favoritter-og-paminnelser").load("index.php5", {op: "ViewFrontUserFavorites"} );
		//	});
			
			$('div.favoritter-og-paminnelser').oneTime(1000, "initButtons", function() {
				initFavButtons("div.favoritter-og-paminnelser div.program a.btn.favorite");
				initReminderButtons("div.favoritter-og-paminnelser div.program a.btn.reminder");
			});
		
		}
		else {
//			$('div.favoritter-og-paminnelser').click(function(){
//				displayLogin();
//				return false;
//			});
			
			
		}
	
	}
	else {
		$('input.alertRadio').click(function(){
			if($(this).attr('id') == 'radioAlert5Min'){
				$.post("index.php5", { op: "ChangeAlertDelay", alertDelay: '5'});
			}else if($(this).attr('id') == 'radioAlert30Min'){
				$.post("index.php5", { op: "ChangeAlertDelay", alertDelay: '30'});
			}else if($(this).attr('id') == 'radioAlert60Min'){
				$.post("index.php5", { op: "ChangeAlertDelay", alertDelay: '60'});
			}
		});
	}
	
	initFavButtons("#onTvNow a.btn.favorite"); // Oppdatert på TV akkurat nå
	initFavButtons("div.program a.btn.favorite");
	initFavButtons("div.program-result a.btn.favorite");
	//initFavButtons("div.program-result a.link-favorite");
	initFavButtons("div.movie-entry a.btn.favorite");
	initReminderButtons("div.program a.btn.reminder");
	initReminderButtons("div.movie-entry a.btn.reminder");
	initReminderButtons("div.program-result a.btn.reminder");
	//initReminderButtons("div.program-result a.link-reminder");
	
	$('div.program-result a.link-favorite').click(function() {
		$(this).parent().children('h2.tools').children('a.btn.favorite').trigger('click');
		return false;
	});
	
	$('div.program-result a.link-reminder').click(function() {
		$(this).parent().children('h2.tools').children('a.btn.reminder').trigger('click');
		return false;
	});
}

function initFavButtons(buttons){
	
	
	$(buttons).click(function() {
		
		var btcontainer = $(this).parent();
			
		if ($(btcontainer).attr("class") == "tools"){
			btcontainer = $(btcontainer).parent();
		}
		
		var params = $(btcontainer).attr("id").split("_");
		
		var channelId = params['1'];
		var programId = params['2'];
		var date = params['3'];
		
		var category = $("#"+btcontainer.attr("id")+" div.category").attr("innerHTML");
		var title = $("#"+btcontainer.attr("id")+" div.realtitle").attr("innerHTML");
		
	
		
			
		if ($(this).hasClass("marked")) {
			$(this).addClass("loader");
			
			if(userId){

				addRemoveFavorite("removeFavorite", channelId, programId, title, category, date);
				return false;
			}
			else {
				displayLogin();
				postLoginFunction = "removeFavorite";
				return false;
			}
		}
		else {
			$(this).addClass("loader");
			if(userId){

				addRemoveFavorite("add", channelId, programId, title, category, date);
				return false;
			}
			else {
				displayLogin();
				postLoginFunction = ["addFavorite", channelId, programId, title, category, date ];
				return false;
			}
		
		}
			
	});
	
}

function initReminderButtons(buttons){
	
	
	$(buttons).click(function() {
		
			
		
		var btcontainer = $(this).parent();
		
		if ($(btcontainer).attr("class") == "tools"){
			btcontainer = $(btcontainer).parent();
		}
		
		var params = $(btcontainer).attr("id").split("_");
		
		var channelId = params['1'];
		var programId = params['2'];
		var date = params['3'];
		
		var category = $("#"+btcontainer.attr("id")+" div.category").attr("innerHTML");
		var title = $("#"+btcontainer.attr("id")+" div.realtitle").attr("innerHTML");
		var channelName = $("#"+btcontainer.attr("id")+" div.channelname").attr("innerHTML");
		var startReal = $("#"+btcontainer.attr("id")+" div.startreal").attr("innerHTML");
		var startTimestamp = $("#"+btcontainer.attr("id")+" div.start_timestamp").attr("innerHTML");
		
		if (userId){
			
		
			if (category == "film"){
				$(this).addClass("loader");
				if ($(this).hasClass("marked")) {
					nextAlarm = "0";
					addRemoveAlarm(title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm);
				}
				else {
					nextAlarm = "2"; // episode ( marked )
					addRemoveAlarm(title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm);
				}
			}
			else {
			
				$(this).addClass("loader");
				if ($(this).hasClass("series")) {
					nextAlarm = "2";
					addRemoveAlarm(title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm);
				}
				else if ($(this).hasClass("marked")) {
					nextAlarm = "0";
					addRemoveAlarm(title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm);
				}
				else {
					nextAlarm = "1";
					addRemoveAlarm(title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm);
				}
			
			}
		
			return false;
	
		}
		else { // ikke innlogget
			
			if (category == "film"){
				$(this).addClass("loader");
			
				nextAlarm = "2"; //til episode
				postLoginFunction = ["addAlarm", title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm ];
				displayLogin();
				
			}
			else {
			
				$(this).addClass("loader");
				
				nextAlarm = "1"; //til serie
				postLoginFunction = ["addAlarm", title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm ];
				displayLogin();
				
			
			}
		
			return false;
		}
			
		
	});
}

function addRemoveAlarm(title, channelId, programId, date, category, startTimestamp, startReal, channelName, nextAlarm, userId) {
	// Check login
	if (userId == undefined) {
		var userId = $('.program-info div#program-details-userid').attr("innerHTML");
	}
	
	//if (userId != "") {

		$.post("index.php5", { op: "AddRemoveAlert", date: date, alertTime: nextAlarm, title: title, channelId: channelId, programId: programId, category: category, startTimestamp: startTimestamp, startReal: startReal, channelName: channelName }, addRemoveAlertCallback );
		
		// Update icons
	//}
	//else {
	//	postLoginFunction = "addRemoveAlert";
	//	displayLogin();	
	//}
	
	
		
	
	return false;
		
}

function addRemoveAlertCallback(responseText, textStatus, XMLHttpRequest) {
	var response = eval("(" + responseText + ")");

	if (response.status == 'ok') {
		
		
			$.each( response.elements, function(i, n){
				
				
				var progid = n.split("div#prog");
				
				progid = progid['1'];
				
				if (nextAlarm == "1"){ // marked series
				
					if (parentFrontPage == "ViewFavoritesReminders"){
						$("div#progAlerts"+progid+" a.btn.reminder").addClass("marked");
						$("div#progAlerts"+progid+" a.btn.reminder").addClass("series");
						$("div#progAlerts"+progid+" a.btn.reminder").removeClass("loader");
						
						$("div#progFavs"+progid+" a.btn.reminder").addClass("marked");
						$("div#progFavs"+progid+" a.btn.reminder").addClass("series");
						$("div#progFavs"+progid+" a.btn.reminder").removeClass("loader");
					}
					else {
						$("div#progTop"+progid+" a.btn.reminder").addClass("marked");
						$("div#progTop"+progid+" a.btn.reminder").addClass("series");
						$("div#progTop"+progid+" a.btn.reminder").removeClass("loader");
						
	//					$("div#progMovie"+progid+" a.btn.reminder").addClass("marked");
	//					$("div#progMovie"+progid+" a.btn.reminder").addClass("series");
	//					$("div#progMovie"+progid+" a.btn.reminder").removeClass("loader");
					}

				}
				else if (nextAlarm == "2"){ // marked
					
				
					
					if (parentFrontPage == "ViewFavoritesReminders"){
						$("div#progAlerts"+progid+" a.btn.reminder").addClass("marked");
						$("div#progAlerts"+progid+" a.btn.reminder").removeClass("series");
						$("div#progAlerts"+progid+" a.btn.reminder").removeClass("loader");
						
						$("div#progFavs"+progid+" a.btn.reminder").addClass("marked");
						$("div#progFavs"+progid+" a.btn.reminder").removeClass("series");
						$("div#progFavs"+progid+" a.btn.reminder").removeClass("loader");
					}
					
					else {
						$("div#progTop"+progid+" a.btn.reminder").addClass("marked");
						$("div#progTop"+progid+" a.btn.reminder").removeClass("series");
						$("div#progTop"+progid+" a.btn.reminder").removeClass("loader");
						
						$("div#progMovie"+progid+" a.btn.reminder").addClass("marked");
						$("div#progMovie"+progid+" a.btn.reminder").removeClass("series");
						$("div#progMovie"+progid+" a.btn.reminder").removeClass("loader");
					}
				}
				
				else {
					
					if (parentFrontPage == "ViewFavoritesReminders"){
						$("div#progAlerts"+progid+" a.btn.reminder").removeClass("marked");
						$("div#progAlerts"+progid+" a.btn.reminder").removeClass("series");
						$("div#progAlerts"+progid+" a.btn.reminder").removeClass("loader");
						
						$("div#progFavs"+progid+" a.btn.reminder").removeClass("marked");
						$("div#progFavs"+progid+" a.btn.reminder").removeClass("series");
						$("div#progFavs"+progid+" a.btn.reminder").removeClass("loader");
					}
					else {
						$("div#progTop"+progid+" a.btn.reminder").removeClass("marked");
						$("div#progTop"+progid+" a.btn.reminder").removeClass("series");
						$("div#progTop"+progid+" a.btn.reminder").removeClass("loader");
						
						$("div#progMovie"+progid+" a.btn.reminder").removeClass("marked");
						$("div#progMovie"+progid+" a.btn.reminder").removeClass("series");
						$("div#progMovie"+progid+" a.btn.reminder").removeClass("loader");
					}
				}
				
			});

			if (parentFrontPage == "ViewFavoritesReminders"){
				window.location.href = "index.php5?op=ViewFavoritesReminders";
			}
			else {
				
				$("div.favoritter-og-paminnelser").load("index.php5", {op: "ViewFrontUserFavorites"} );
				$('div.favoritter-og-paminnelser').oneTime(1000, "initButtons", function() {
					initFavButtons("div.favoritter-og-paminnelser div.program a.btn.favorite");
					initReminderButtons("div.favoritter-og-paminnelser div.program a.btn.reminder");
				});
			
			}

	}	
}

function displayLogin() {
	$('.dbAd').css('visibility', 'hidden');
	jQuery.facebox('<div id="login_content">' +
						'<h3>Du må logge inn for å benytte denne tjenesten.</h3>' +
						'<p id="login-ajax-error-text"></p>' +
						'<form action="" method="post" id="loginformAjax" name="login">' +
							'<input type="hidden" name="sid" value="101"> ' +
							'<input type="hidden" name="target" value="' + returnUrl + '"> ' +
							'<input type="hidden" name="action" value="">' +
							'<div>' +
								'<label for="login-ajax-username">E-post</label> <input name="login-ajax-username" id="login-ajax-username" type="text"	size="20" class="inputtext"	value="" tabindex="1">' +
							'</div>' +
							'<div>' +
								'<a href="http://www.se.no/konto/?op=LostPassword&target='+ returnUrl +'" id="lost_pwd">Glemt passord?</a> <label for="login-ajax-password">Passord</label> <input	name="login-ajax-password" id="login-ajax-password" type="password" size="20" class="inputtext" value="" tabindex="2"/>' +
							'</div>' +
							'<button id="submit" class="inputsubmit" value="Login" name="dologin" type="submit" tabindex="3">Logg inn</button>' +
							' eller <a href="http://www.se.no/konto/?op=RegisterUser&target=' + returnUrl + '">registrer deg her</a>  <p>Har du allerede bruker på Db.no? Da kan du logge inn med denne!</p>' +
						'</form>' +
					'</div>');	
	
	$("input#login-username").focus();
	//document.login.login-username.focus();
	
	$('form#loginform').submit(function () {
		// var postVars = "op=LoginUser&response=json&serviceid=101&username=" + emailAddress + "&password=" + pwd;
		
		$("iframe#crosslogin").attr("src", "http://konto.dagbladet.no/index.php5?op=LoginUser&response=json&sid="+serviceId+"&username=" + $('input#login-username').attr("value") + "&password=" + $('input#login-password').attr("value") + "&target="+ returnUrl);
		
		$.post("http://www.se.no/konto/index.php5", { op: "LoginUser", response: "json", sid: serviceId, username: $('input#login-username').attr("value"), password: $('input#login-password').attr("value") }, loginCallback );
		$('.dbAd').css('visibility', 'visible');
		return false;
	});
	$('form#loginformAjax').submit(function () {
		// var postVars = "op=LoginUser&response=json&serviceid=101&username=" + emailAddress + "&password=" + pwd;
		
		$("iframe#crosslogin").attr("src", "http://konto.dagbladet.no/index.php5?op=LoginUser&response=json&sid="+serviceId+"&username=" + $('input#login-ajax-username').attr("value") + "&password=" + $('input#login-ajax-password').attr("value") + "&target="+ returnUrl);
		
		$.post("http://www.se.no/konto/index.php5", { op: "LoginUser", response: "json", sid: serviceId, username: $('input#login-ajax-username').attr("value"), password: $('input#login-ajax-password').attr("value") }, loginCallbackAjax );
		$('.dbAd').css('visibility', 'visible');
		return false;
	});
	
	
	$('#facebox_overlay').click(function(){
		$('.dbAd').css('visibility', 'visible');
	});
	$('a.close').click(function(){
		$('.dbAd').css('visibility', 'visible');
	});
}

function crossLogin(){

		$('form#loginform').oneTime(500, "crossForm", function() {
			window.location.href = "index.php5";
		});
}

function loginCallback(responseText, textStatus, XMLHttpRequest) {
	
	
	var response = eval("(" + responseText + ")");
	
	if (response.userid != null) {
		if (postLoginFunction["0"] == 'addFavorite') {
			doRefresh = true;
			userId = response.userid;
			addRemoveFavorite("add",postLoginFunction["1"],postLoginFunction["2"],postLoginFunction["3"],postLoginFunction["4"],postLoginFunction["5"]);
			
		}
		else if(postLoginFunction["0"] == 'addAlarm'){
			doRefresh = true;
			userId = response.userid;
			addRemoveAlarm(postLoginFunction["1"], postLoginFunction["2"], postLoginFunction["3"], postLoginFunction["4"], postLoginFunction["5"], postLoginFunction["6"], postLoginFunction["7"], postLoginFunction["8"], postLoginFunction["9"]);
		}
		
		else {
			
//			alert(response.userid);
//			window.location.href = "index.php5";
			
			crossLogin();		

//			personalize(response);
//			$.facebox.close(); 
		}

		postLoginFunction = false;
		
	}
	else if (response.errors) {
		for ( var i=0, len=response.errors.length; i<len; ++i ){

			if (response.errors[i] == 403 || response.errors[i] == 501) {
				$('p#login-error-text').attr("innerHTML", "<p>Feil e-post/passord</p>");
			} else if (response.errors[i] == 404) {
				$('p#login-error-text').attr("innerHTML", "<p>Brukeren finnes ikke. Har du registert deg?</p>");
			}
		}
	}
}

function loginCallbackAjax(responseText, textStatus, XMLHttpRequest) {
	
	
	var response = eval("(" + responseText + ")");
	
	if (response.userid != null) {
		if (postLoginFunction["0"] == 'addFavorite') {
			doRefresh = true;
			userId = response.userid;
			addRemoveFavorite("add",postLoginFunction["1"],postLoginFunction["2"],postLoginFunction["3"],postLoginFunction["4"],postLoginFunction["5"]);
			
		}
		else if(postLoginFunction["0"] == 'addAlarm'){
			doRefresh = true;
			userId = response.userid;
			addRemoveAlarm(postLoginFunction["1"], postLoginFunction["2"], postLoginFunction["3"], postLoginFunction["4"], postLoginFunction["5"], postLoginFunction["6"], postLoginFunction["7"], postLoginFunction["8"], postLoginFunction["9"]);
		}
		else {
//			alert(response.userid);
//			window.location.href = "index.php5";
			window.location.reload(true);
			//crossLogin();		

//			personalize(response);
//			$.facebox.close(); 
		}

		postLoginFunction = false;
		
	}
	else if (response.errors) {
		for ( var i=0, len=response.errors.length; i<len; ++i ){

			if (response.errors[i] == 403 || response.errors[i] == 501) {
				$('p#login-ajax-error-text').attr("innerHTML", "<p>Feil e-post/passord</p>");
			} else if (response.errors[i] == 404) {
				$('p#login-ajax-error-text').attr("innerHTML", "<p>Brukeren finnes ikke. Har du registert deg?</p>");
			}
		}
	}
}

function addFavoriteCallback(responseText, textStatus, XMLHttpRequest) {
	var response = eval("(" + responseText + ")");

	if (response.status == 'ok') {
		
		
		if (doRefresh) {
			window.location.href = "index.php5";
		}
		else {
			$('.program-info .tools a.favoritt').unbind('click'); 
			$('.program-info .tools a.favoritt').addClass("favoritt-active");
			$('.program-info .tools a.favoritt-active').click(function() {return addRemoveFavorite("remove");});
			
			$.each( response.elements, function(i, n){
				
				var progid = n.split("div#prog");
				
				progid = progid['1'];
				$("div#progNow"+progid+" a.btn").removeClass("loader");
				$("div#progNow"+progid+" a.btn").addClass("marked");
				
				$("div#progNext"+progid+" a.btn").removeClass("loader");
				$("div#progNext"+progid+" a.btn").addClass("marked");
				
				$("div#progTop"+progid+" a.btn.favorite").removeClass("loader");
				$("div#progTop"+progid+" a.btn.favorite").addClass("marked");
				
				$("div#progMovie"+progid+" a.btn.favorite").removeClass("loader");
				$("div#progMovie"+progid+" a.btn.favorite").addClass("marked");
				
				if (parentFrontPage == "ViewFavoritesReminders"){
					$("div#progAlerts"+progid+" a.btn.favorite").removeClass("loader");
					$("div#progAlerts"+progid+" a.btn.favorite").addClass("marked");
					
					$("div#progFavs"+progid+" a.btn.favorite").removeClass("loader");
					$("div#progFavs"+progid+" a.btn.favorite").addClass("marked");
				}
				
			});
			
					
			if (parentFrontPage == "ViewFavoritesReminders"){
				window.location.href = "index.php5?op=ViewFavoritesReminders";
			}
			
			else {
			
				$("div.favoritter-og-paminnelser").load("index.php5", {op: "ViewFrontUserFavorites"} );
				$('div.favoritter-og-paminnelser').oneTime(1000, "initButtons", function() {
					initFavButtons("div.favoritter-og-paminnelser div.program a.btn.favorite");
					initReminderButtons("div.favoritter-og-paminnelser div.program a.btn.reminder");
				});
			
			}
			
		}
		
	}
	
	
}

function removeFavoriteCallback(responseText, textStatus, XMLHttpRequest) {
	
	var response = eval("(" + responseText + ")");

	if (response.status == 'ok') {
		
		if (doRefresh) {
			window.location.href = "index.php5";
		}
		else if (parentFrontPage == "ViewFavoritesReminders"){
			window.location.href = "index.php5?op=ViewFavoritesReminders";
		}
		else {
		
			$('.program-info .tools a.favoritt-active').unbind('click'); 
			$('.program-info .tools a.favoritt').removeClass("favoritt-active");
			$('.program-info .tools a.favoritt').click(function() {return addRemoveFavorite("add");});
			
			$.each( response.elements, function(i, n){
				
			var progid = n.split("div#prog");
					
				progid = progid['1'];
				$("div#progNow"+progid+" a.btn").removeClass("loader");
				$("div#progNow"+progid+" a.btn").removeClass("marked");
					
				$("div#progNext"+progid+" a.btn").removeClass("loader");
				$("div#progNext"+progid+" a.btn").removeClass("marked");
				
				$("div#progTop"+progid+" a.btn.favorite").removeClass("loader");
				$("div#progTop"+progid+" a.btn.favorite").removeClass("marked");
				
				$("div#progMovie"+progid+" a.btn.favorite").removeClass("loader");
				$("div#progMovie"+progid+" a.btn.favorite").removeClass("marked");
				
			});
			
			$("div.favoritter-og-paminnelser").load("index.php5", {op: "ViewFrontUserFavorites"} );
			$('div.favoritter-og-paminnelser').oneTime(1000, "initButtons", function() {
				initFavButtons("div.favoritter-og-paminnelser div.program a.btn.favorite");
			});
		
		}
		
	}
}

function addRemoveFavorite(mode, channelId, programId, title, category, date, userId ) {

	
	if (userId == undefined) {
		var userId = $('.program-info div#program-details-userid').attr("innerHTML");
	}
	
	if (userId != "") {
	
		if (category == "film"){
			var favoriteType  = "single";
		}
		else {
			var favoriteType = "series";
		}
		
//		favoriteType = "";
		
		if (mode == 'add') {
			var op = "AddFavorite";
			var callback = "addFavoriteCallback";
		}
		else {
			var op = "RemoveFavorite";
			var callback = "removeFavoriteCallback";
		}
		
		$.post("index.php5", { op: op, date: date, title: title, channelId: channelId, programId: programId, category: category, favoriteType: favoriteType }, eval(callback) );
		
	}
	else {
		postLoginFunction = "addFavorite";
		displayLogin2();	
	}
	return false;
}

function toggleAlternatives() {
	
	if ( $("#alternatives-container").css( "display") == "block") {
		$('.ad-972x150').css('visibility', 'visible');
		$("#alternatives-container").css( "display", "none");
		$("#alternatives-content-container").attr( "innerHTML", "");
	}
	else {
		$('.ad-972x150').css('visibility', 'hidden');
//		resetListings();
		$("#alternatives-container").css( "display", "block");
		$("#alternatives-content-container").attr( "innerHTML", '<div class="loader">Laster alternativer...<br/><img src="http://gfx.dagbladet.no/tv-program/ikoner/whiteonblack.gif" /></div>');
		$("#alternatives-content-container").load("index.php5", {op: "ViewAlternatives"}, initAlternatives);
	}
	
}

function initAlternatives() {
	
	var altChannelClick = function() {
		$(this).toggleClass("channel-selected");
		return false;
	};
	
	$('.channelsSortable').sortable({ 
		containment: 'parent',
		update: function(event, ui) { 
            ui.item.unbind("click");
            ui.item.one("click", function (event) { 
                event.stopImmediatePropagation();
                $(this).click(altChannelClick);
            }); 
		}
	});
	$('.channelsSortable').disableSelection();	
	
	
	$('#channels div.alt-channel').click(altChannelClick);
	
	$('button#button-alternatives-save').click(function() {
		var userChannels = new Array();
		var counter = 0;
		$('div.channel-selected').each(function(){
			var params = $(this).attr("id").split("_");
			//$(this).css("display", "none");
			userChannels[counter] = params[2];
			++counter;
		});
		//alert("index.php5?op=SaveUserAlternatives&channels=" + userChannels);
		window.location.href = "index.php5?op=SaveUserAlternatives&returnTo=tv&channels=" + userChannels;
		return false;
	});	
	
	$('a.channels-preset').click(function() {
		var params = $(this).attr("href").split("_");
		var channels = params[1].split(",");

		resetAlternativesChannels();
		
		
		$.each(channels, function(intIndex, objValue) {

			$("#channels div#alt_channel_" + objValue).addClass("channel-selected");
		});

		return false;
	});
	
	$('a#channels-reset').click(function() {
		resetAlternativesChannels();
		return false;
	});
		
	$('a#channels-setall').click(function() {
		setAlternativesChannels();
		return false;
	});
	
	
}

function resetAlternativesChannels() {
	$('#channels div.alt-channel').removeClass("channel-selected");
}

function setAlternativesChannels() {
	$('#channels div.alt-channel').addClass("channel-selected");
}

