String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};

var userId = '';
//VGiD
function getLoggedInUser(response) {
   if (typeof (response.session) != 'undefined' && response.session != null && response.session != false) {
	   // logged in and connected user
       $("#VGiD").html('Logget inn som <a href="'+VGS.getAccountURI()+'">'+response.session.displayName+'</a> | <a href="javascript:;" onclick="VGS.Auth.logout();">Logg ut</a>');
       userId = response.session.id;
       $("#news").slideUp('slow');
       $('#arrowDown').hide();
   } else {
       // No valid session found
       $("#VGiD").html('<a href="' + VGS.getLoginURI() + '">LOGG INN</a><img src="http://static.vg.no/gfx/vgID16x16.png" alt="VGiD Login" />');
       userId = '';
       $("#news").slideDown('slow').fadeOut('fast').fadeIn('slow');
       $('#arrowDown').show();
   }
}

function isLoggedIn() {
	return (userId != '');
}

$(document).ready(function(){
	resizeWindow();
    try {
        VGS.Event.subscribe('auth.sessionChange', getLoggedInUser);
        VGS.Event.subscribe('auth.login', getMyFavorites);
        VGS.init({client_id : '4e70a7cee962dd83650f0000', timeout: 15000});                
    } catch (error) {
    	alert(error);
    }
	
	var locationstr = window.location.hash.replace('#', '');
	var locationvars = locationstr.split('::');
		
	$.each(locationvars, function(i,item) {
		var keyvalue = item.split('=');
		if (keyvalue[0] == 'd') {
			var typeelement = $("#days li a[href='#" + keyvalue[1] + "']");
			if (typeelement.length > 0) {
				$("#days li a.today").removeClass('today');
				typeelement.addClass('today');
				dateProgram = keyvalue[1];
			}
		} else if (keyvalue[0] == 't') {
			var typeelement = $("#progcontent li a[href='#" + keyvalue[1] + "']");
			if (typeelement.length > 0) {
				$("#progcontent li.active").removeClass('active');
				typeelement.parent().addClass('active');
				programType = keyvalue[1];
			}
		}
	});

    if (readCookie('channels') != null) {
        channelIds = readCookie('channels');
    }
    
    activeChannelIds = channelIds = channelIds.split(',');

    getFavorites();
    getMoviesOnTV();
    loadChannels();

	$('#faves .channel .title').live('click', function() {
		var programId = $(this).prev('dt').attr("id");
		var thisel = $(this);
		var scrollValue = thisel.parents('dl').scrollTop();
		if (thisel.next().hasClass('description')) { 
			thisel.next('dd').remove();
		} else {
			$.get("programinfo.php?prog=" + programId, function(data) {
				thisel.after('<dd class="description">' + data + '</dd>');
				thisel.next('dd').slideDown('slow');
				thisel.parents('dl').scrollTop(scrollValue);
			});
		}
		return false;
	});
	
	$('ul li strong.title').live('click', function() {
		var programId = $(this).next('span').attr("id");
		var thisel = $(this).next('span');
		if (thisel.next('span').hasClass('description')) { 
			thisel.next('span').remove();
		} else {
			$.get("programinfo.php?prog=" + programId, function(data) {
				thisel.after('<span class="description">' + data + '</span>');
				thisel.next('span').slideDown('slow');
			});
		}
		return false;
	});
	
	$('#column .columnContent.faves dt, #vgfilm dt').live('click', function() {
		var programId = $(this).attr("id").replace('p','');
		var thisel = $(this).next('dd').next('dd');
		
		if (thisel.next('dd').hasClass('description')) { 
			thisel.next('dd').remove();
		} else {
			$.get("programinfo.php?prog=" + programId, function(data) {
				thisel.after('<dd class="description">' + data + '</dd>');
				thisel.next('dd').slideDown('slow');
			});
		}
		return false;
	});
	
	$('.description').live('click', function() {
		$(this).remove();
	});
	
    $('#days li a').click(function() {
    	if ($(this).hasClass('today')) {
    		return false;
    	}
        $('#days li a.today').removeClass('today');
        $(this).addClass('today');
        dateProgram = this.hash.slice(1);
        reloadSchedule();
        return false;
    });
    
    $('#helpbutton a').click(function() {
        $('#infobox .innerinfo').css('display', 'none');
    	$('#infobox #help').css('display', 'inline');
    	$('#infobox').show('fast');
    	return false;
    });
    
    $('#faves .channel h2').live('click', function() {
        var chan = $(this).parent().attr('id').replace(/channel/g, '');
        scrollToProgram(chan);
        return false;
    });
    
    $('#editchannels').click(function() {
    	if (!isLoggedIn()) {
    		alert("Du må være innlogget for å få tilgang til denne funksjonen.");
    		return;
    	}
        $('#infobox .innerinfo').css('display', 'none');
        $('#infobox #packages').css('display', 'inline');
		for (var id in activeChannelIds) {
			$('#chan' + activeChannelIds[id]).attr('checked', 'checked');
		}
    	$('#infobox').show('fast');
    	return false;
    });
    
    $('#closeinfobox').live('click', function() {
    	$('#infobox').hide('slow');
    	return false;
    });
    
    $('#closenews').live('click', function() {
    	$('#news').slideUp('slow');
    	$('#arrowDown').hide();
    	return false;
    });
    
    $('#packages .selectall').live('click', function() {
        var packid = $(this).attr('id');
        if ($(this).hasClass('checked')) {
            $('#chan' + packid + ' input:checkbox').removeAttr('checked');
            $(this).removeClass('checked');
        } else {
            $('#chan' + packid + ' input:checkbox').attr('checked', 'checked');
            $(this).addClass('checked');
        }
    });
    
    $('#savechannels, #closeinfobox2').live('click', function() {
        saveChannels();  
        $('#infobox').hide('slow');
    });

    $('#channelpacks li a').click(function() {
    	if ($(this).parent().hasClass('active')) {
    		return false;
    	}
        $('#channelpacks li.active').removeClass('active');
        $(this).parent().addClass('active');
        
        channels = this.hash.slice(1);
        if (channels == 0) {
        	$('.buttons').show();
        	activeChannelIds = channelIds;
        	personalList = false;
        } else {
        	$('.buttons').hide();
        	activeChannelIds = channels.split(',');
        	personalList = true;
        }
        
        loadChannels();
        getMoviesOnTV();
        return false;
    });
    
    $('a.fav, span.fav').live('click', function() {
    	if (!isLoggedIn()) {
    		alert("Du må være innlogget for å få tilgang til denne funksjonen.");
    		return;
    	}
    	var programId = $(this).parent().attr("id");
    	if ($(this).next().hasClass('past')) { return false; }
    	
    	if ($(this).hasClass('active')) {
    		$('.channel #' + programId + ' a.fav').removeClass("active");
    		$('#otherfaves #' + programId + ' a.fav').removeClass("active");
    		$(this).removeClass("active");
    		$.post("set-fav.php", { remove: 1, program: programId, user: userId }, function(data) {
    			getMyFavorites();
    		});
    	} else {
    		$(this).addClass("active");
    		$.post("set-fav.php", { program: programId, user: userId }, function(data) {
    			getMyFavorites();
    		});
    	}
		return false;
    });
    
    $('#progcontent li a').click(function() {
    	if ($(this).parent().hasClass('active')) {
    		return false;
    	}
        $('#progcontent li.active').removeClass('active');
        $(this).parent().addClass('active');
        
        var type = this.hash.slice(1);
        if (type == programType) {
        	return false;
        }
        showType(type);
        return false;
    });
	
    $('#time li a').click(function() {
    	if ($(this).hasClass('active')) {
    		return false;
    	}
    	$('#time li a.active').removeClass('active');
    	$(this).addClass('active');
    	var hour = this.hash.slice(1);
    	for (var id in activeChannelIds) {
    		chanId = activeChannelIds[id];
    		if (hour == '') {
    			scrollToProgram(chanId);
    		} else {
    			scrollToProgram(chanId, 'hour'+hour);
    		}
        }
    	return false;
    });
    
    $("#quickpick").change(function() {
        var channels = $(this).attr("value");
        if (channels == 0) {
            return false;
        }
        $('.channelpack input:checkbox').removeAttr('checked');
        channels = channels.split(',');
        for (var id in channels) {
            $('#chan' + channels[id]).attr('checked', 'checked');
        }
        return false;
    });

	$('#sortchannels').click(function() {
		if (!isLoggedIn()) {
    		alert("Du må være innlogget for å få tilgang til denne funksjonen.");
    		return;
    	}
		if ($(this).hasClass('ferdig')) {
			$(this).removeClass('ferdig').html('Sorter kanalene');
            $('#inlineannonse').show();
            $('.proglist dl').show();
            $('.proglist').sortable('disable');
            $('#saveChannelSort').remove();
            for (var id in activeChannelIds) {
                scrollToProgram(activeChannelIds[id]);
            }			
		} else {
            $('.proglist dl').hide();
            $('.proglist').sortable({cursor: 'move', helper: 'clone', update: function(event, ui) {
                channelIds = $('.proglist').sortable('toArray').toString().replace(/channel/g, '');
                channelIds = channelIds.replace(/inlineannonse/g, '').replace(',,',',');
                $.post("set-channels.php", { channelIds: channelIds, user: userId });
                createCookie('channels', channelIds, 365);
                activeChannelIds = channelIds = channelIds.split(',');
            }}).disableSelection().sortable('enable');
            $('#inlineannonse').hide();
            $(this).addClass('ferdig').html('Lagre sortering');
            $('.proglist').after('<p><a href="#" id="saveChannelSort">Lagre sortering</a>');
        }
	});
	
	$('#saveChannelSort').live('click', function() {
		$(this).remove();
		$('#sortchannels').removeClass('ferdig').html('Sorter kanalene');
        $('#inlineannonse').show();
        $('.proglist dl').show();
        $('.proglist').sortable('disable');
        for (var id in activeChannelIds) {
            scrollToProgram(activeChannelIds[id]);
        }
        return false;
	})
	
	$("#searchWord").attr('autocomplete', 'off').autocomplete({ minLength: 2, delay: 300, source: 'search.php', 
		select: function(event, ui) { return; }
	}).data("autocomplete")._renderItem = function( ul, item ) {
		return $("<li></li>").data("item.autocomplete", item).append(item.info).appendTo(ul);
	};
	
	$(window).resize(function() {
		resizeWindow();
	});
	// Autorefresh every 5 min
	setInterval("reloadSchedule()", 300000);
});

function resizeWindow() {
	var winwidth = $(window).width();
	if (winwidth >= 2246) {
		$('#footer').css('width', '1995px');
	    $('#column').css('left', '2005px');
	} else if (winwidth >= 1996) {
		$('#footer').css('width', '1745px');
	    $('#column').css('left', '1755px');
	} else if (winwidth >= 1746) {
		$('#footer').css('width', '1495px');
	    $('#column').css('left', '1505px');
	} else if (winwidth >= 1496) {
		$('#footer').css('width', '1245px');
	    $('#column').css('left', '1255px');
	} else if (winwidth >= 1246){
		$('#footer').css('width', '995px');
	    $('#column').css('left', '1005px');
	} else {
		$('#footer').css('width', '745px');
	    $('#column').css('left', '755px');
	}
}

function getSchedule(channel, day, reload) {
    var siste = cssclass = '';
    var programdata = '';
    var hour = 0;
    showLoader();
    $.ajax({
        type: "GET",
        url: "schedule.php?channel=" + channel + "&day=" + day,
        dataType: "json",
        cache: true,
        success: function(data) {
    	
			$.each(data, function(i,item) {
				if (item.type == 'channel' && !reload) {
		        	$("#channel" + channel).append('' +
		    			'<img class="logo" src="logo/' + item.logo + '" alt="Logo: ' + item.name + '" />' +
		    			'<h2>' + item.name + '</h2>' +
		    			'<dl></dl>');
		        } else if (item.type == 'program') {
		        	siste = item.stop;
		        	thistime = item.programid.split('_')[1];
		        	cssclass = '';
		        	thishour = thistime.substr(8,2);
		        	if (hour != thishour) {
		        		cssclass += ' hour' + thishour;
		        	}
		        	hour = thishour;
		        	
		        	if (timenow >= thistime && timenow < item.timestamp) {
		        		cssclass += ' now';
		        	} else if (timenow > thistime) {
		        		cssclass += ' past';
		        	}
		        	lastTime = item.timestamp;
		        	
		        	programdata +=  '<dt id="' + item.programid + '" class="cat' + item.category + '">' + 
		    			'<a class="fav" href="#">Favoritt</a> <span class="time' + cssclass + '">' + item.start + '</span></dt>' +
		    			'<dd class="title' + cssclass + '">' + item.title + '</dd>';
		        }
		    });
			cssclass = '';
			if(timenow > lastTime) { cssclass = ' now'; }
	    	programdata += '<dt><span class="time slutt' + cssclass + '">' + siste + '</span></dt>' +
	                '<dd class="title slutt' + cssclass + '">Slutt p&aring; sending</dd>';
	        $("#channel" + channel + " dl").html('' + programdata);
	        showChannelType(channel);
	        showLoader();
	        scrollToProgram(channel);
	    }
    });
}

function loadChannels() {
    $(".proglist").html('');
    var c = 1;
    for (var id in activeChannelIds) {
    	if (c++ == 3) {
    		$(".proglist").append('<div class="annonse" id="inlineannonse"><img src="css/admark_left.gif" id="admark" /><iframe width="240" height="268" scrolling="no" marginheight="0" marginwidth="0" frameborder="0" src="http://ads.vg.no/adstream_sx.ads/vg.no/tv-guide/@Position2"></iframe></div>');
    	}
        chanId = activeChannelIds[id];
        $(".proglist").append('<div class="channel" id="channel' + chanId + '"></div>');
        getSchedule(chanId, dateProgram);
    }
}

function saveChannels() {
    var tempChannelIds = '';
    
    for (var id in activeChannelIds) {
        chanId = activeChannelIds[id];
        if ($("#chan" + chanId).is(':checked')) {
        	tempChannelIds += 'chan' + chanId + ',';
        }
    }
    
    $('.channelpack input:checked').each(function(i) {
        if (!$(this).hasClass('selectall')) {
            chanId = $(this).attr('id');
            if (!tempChannelIds.match(chanId + ',')) {
            	tempChannelIds += chanId + ',';
            }
        }
    });
    
    tempChannelIds = tempChannelIds.replace(/chan/g, '').replace(/,$/, '');
    if (tempChannelIds != '') {
    	$.post("set-channels.php", { channelIds: tempChannelIds, user: userId });
        createCookie('channels', tempChannelIds, 365);
        activeChannelIds = channelIds = tempChannelIds.split(',');
    }
    
    $('#infobox').hide('slow');
    loadChannels();
}

function reloadSchedule() {
	getFavorites();
	getMoviesOnTV();
	
	for (var id in activeChannelIds) {
		chanId = activeChannelIds[id];
        getSchedule(chanId, dateProgram, true);
    }
}

function getFavorites() {
	var programdata = '';
    $.ajax({
        type: "GET",
        url: "fav.php?day=" + dateProgram,
        dataType: "json",
        cache: true,
        success: function(data) {
			$.each(data, function(i,item) {
				if (item.type == 'heading') {
		        	$('#otherfaves p.info').html(item.value);
		        } else if (item.type == 'readmore') {
		        	$('#otherfaves p.lesmer').html(item.value);
		        } else if (item.type == 'program') {
		        	
		        	programdata += '<dt id="p' + item.programid + '">' + item.title + '</dt>' +
		        		'<dd class="logo"><img alt="' + item.channel + '" src="logo/' + item.logo + '" /></dd>' + 
		        		'<dd id="' + item.programid + '"><a href="#" class="fav">Favoritt</a><span class="percent">' + item.percent + '%</span>' + item.start + ' - ' + item.stop + '</dd>';
		        }
		    });
	        $("#otherfaves dl").html('' + programdata);
	    }
    });
}

function getMyFavorites() {
	var programdata = '';
	if (!isLoggedIn()) {
		return;
	}
    $.ajax({
        type: "POST",
        url: "myfav.php?day=" + dateProgram + '&user=' + userId,
        dataType: "json",
        success: function(data) {
    	
    		if (data.length == 2) {
				programdata += '<dd>Du har ikke markert noen programmer du vil se denne dagen</dd>';
	        }
			$.each(data, function(i,item) {
				if (item.type == 'favchannels') {
		        	if (item.value != '' && item.value != activeChannelIds.join(',')) {
	        			createCookie('channels', item.value, 365);
	        			if (typeof(personalList) == 'undefined' || personalList == false) {
		        	        activeChannelIds = channelIds = item.value.split(',');
		        	        var r = confirm("Din kanal-liste har endret seg på serveren. Vil du oppdatere?");
		        	        if (r==true) {
		        	        	loadChannels();
		        	        } else {
		        	        	// Do nothing
		        	        }
	        			}
	        		}
		        } else if (item.type == 'heading') {
		        	$('#myfaves p.info').html(item.value);
		        } else if (item.type == 'program') {
		        	programdata += '<dt id="p' + item.programid + '">' + item.title + '</dt>' +
		        		'<dd class="logo"><img alt="' + item.channel + '" src="logo/' + item.logo + '" /></dd>' + 
		        		'<dd id="' + item.programid + '"><a href="#" class="fav active">Favoritt</a> ' + item.start + ' - ' + item.stop + '</dd>';
		        		$('.channel #' + item.programid + ' a.fav').addClass("active");
		        		$('#otherfaves #' + item.programid + ' a.fav').addClass("active");
		        }
		    });
	        $("#myfaves dl").html('' + programdata);
	    }
    });
}

function getMoviesOnTV() {
	var programdata = '';
    $.ajax({
        type: "GET",
        url: "reviewed.php?day=" + dateProgram + "&channels=" + activeChannelIds.join(','),
        dataType: "json",
        cache: true,
        success: function(data) {
			$.each(data, function(i,item) {
				
	    		if (data.length == 1) {
		        	programdata += '<dd>Det er ingen omtalte filmer for denne dagen. Pr&oslash;v igjen senere.</dd>';
		        }
				if (item.type == 'heading') {
		        	$('#vgfilm p.info').html(item.value);
		        } else if (item.type == 'program') {
					if (item.dice != 0) {
		        		dice = '<img alt="Terningkast ' + item.dice + '" src="images/terning_' + item.dice + '.gif"/>';
		        	} else {
		        		dice = '';
		        	}
		        	programdata += '<dt id="p' + item.programid + '">' + item.title + '</dt>' +
		        		'<dd class="terning">' + dice + '</dd>' +
		        		'<dd>' + item.channel + ' kl. ' + item.start + '</dd>';
		        }
		    });
	        $("#vgfilm dl").html('' + programdata);
	    }
    });
}

function showType(type) {
	$('.noprograms').remove();
    if (type == '0') {
    	$('.channel dt').show().next('dd').show();
    	$('#content .proglist .channel dl').css('height', '220px');
    } else {
    	$('.channel dt').hide().next('dd').hide();
    	$('.channel dt.cat' + type).show().next('dd').show();
    	$('#content .proglist .channel dl').css('height', '100px');
    }

    programType = type;
    
    for (var id in activeChannelIds) {
		chanId = activeChannelIds[id];
		var size = $('#channel' + chanId + ' dl dt:visible').size()
		if (!size) {
			$('#channel' + chanId + ' dl').prepend('<dt class="noprograms"></dt><dd class="noprograms">Denne kanalen viser ingen programmer av denne programtypen.</dd>');
		}
		scrollToProgram(chanId);
    }
}

function showChannelType(chanId) {
	var type = programType;
    if (type == '0') {
    	$('#channel' + chanId + ' dt').show().next('dd').show();
    	$('#channel' + chanId + ' dl').css('height', '220px');
    } else {
    	$('#channel' + chanId + ' dt').hide().next('dd').hide();
    	$('#channel' + chanId + ' dt.cat' + type).show().next('dd').show();
    	$('#channel' + chanId + ' dl').css('height', '100px');
    }

	var size = $('#channel' + chanId + ' dl dt:visible').size()
	if (!size) {
		$('#channel' + chanId + ' dl').prepend('<dt class="noprograms"></dt><dd class="noprograms title">Denne kanalen viser ingen programmer av denne programtypen.</dd>');
	}
}

function scrollToProgram(channel, hour) {
	if (typeof(hour) == 'undefined') {
		hour = 'now';
		$('#time li a.active').removeClass('active');
		$('#time li a.now').addClass('active');
	}
    $('#channel' + channel + " dl").scrollTop(0);
	var chanOffset = $('#channel' + channel + " dl").offset().top;
    var programOffset = ($('#channel' + channel + " span." + hour).offset() != null) ? $('#channel' + channel + " span." + hour).offset().top : 0;
    if (programOffset != 0) {
    	var pScroll = programOffset - chanOffset - 5;
    	$('#channel' + channel + " dl").scrollTop(pScroll);
    }
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/tv-guide";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

function cleanUp(favlist) {
	favlist = favlist.split(',');
	var favtime = timenow.substr(0,8);
	var newfavlist = ''; 

	for (var id in favlist) {
		thisfav = favlist[id];
		thisindex = thisfav.indexOf('_');
		if (thisindex > 0) {
			if (thisfav.substr(thisindex+1, 8) >= favtime) {
				newfavlist += thisfav + ',';
			}
		}
    }
	return newfavlist;
}

function showLoader() {
	clearTimeout(loader);
	$("#loading:hidden").show();
	loader = setTimeout('hideLoader()', 1000);
}

function hideLoader() {
	$("#loading").hide();
	getMyFavorites();
	showType(programType);
}

