function onKeySimple(e) {		
	var key = document.all ? window.event.keyCode : e.which; // IE Netscape problem
	if(key == 13) {
		$("#aspnetForm").submit();
	}
	return key != 13;
}

jQuery.fn.log = function(msg) {
    if(console)
        console.log("%s: %o", msg, this);
    return this;
};

function resetAdvancedSearch(e) {
    $("input:text").filter(".advsearchtextbox").val('');
    $("select").filter(".advsearchselect").val('');
    return false;
}

function isNumeric(e) {
    if ([e.keyCode||e.which]==8) //allow backspace
        return true;
    if ([e.keyCode||e.which]==9) //allow tabulator
        return true;        
    if ([e.keyCode||e.which] < 48 || [e.keyCode||e.which] > 57)
    e.preventDefault? e.preventDefault() : e.returnValue = false;
}

function LoadArticleIntoTab() {
    $('#loaderbar').fadeIn(100);
    $('#centerContent').load('content/Articles.aspx #ArticleList', function() {
    $('#loaderbar').fadeOut(100);
        $('#centerContent a').click(function() {
            $('#centerContent').load($(this).attr('href') + ' #ArticleContent', function() {
                $('#centerContent a').click(function() {
                    if ($(this).attr('href').indexOf('Default.aspx') != -1) {
                        //load article-list into tab again
                        LoadArticleIntoTab();
                        return false;
                    }
                });
            });
            return false;
        });
    });
}

function LoadNewFilmsIntoTab() {
    $('#loaderbar').fadeIn(100);
    $('#centerContent').load('film/NewFilms.aspx #filmlist', function() {
        $('#loaderbar').fadeOut(100);
        $('.filmlistwrap').click(function() {
            window.location = $(this).children('.filmlistheaderfront').children('a').attr('href');
            return false;
        });
    });
}

function LoadSingleArticleIntoTab(ArticleNum) {
    $('#loaderbar').fadeIn(100);
    $('#centerContent').load('content/page.aspx?id=' + ArticleNum + ' #content-wrapper', function() {
        $('#loaderbar').fadeOut(100);
        $('.filmlistwrap').click(function() {
            window.location = $(this).children('a').attr('href');
        });
    });
}



$(document).ready(function() {

    //make top menu change looks to show active page
    $("#menu-wrapper > ul > li > a").click(function(){
    $("#menu-wrapper > ul > li > a").css("font-weight","normal");
    $(this).css("font-weight","bold");
    });

    $("#tb1").css('background-image', 'url(content/img/portal/container-left-active.gif)');
    $("#tb1 > a").css('background-image', 'url(content/img/portal/container-right-active.gif)');
    if ($(".maintabs").length) LoadNewFilmsIntoTab();
    $(".maintabs a").click(function() {
        try {
            var $thisid = $(this).parent().attr('id');

            switch ($thisid) {
                case 'tb4':
                    LoadSingleArticleIntoTab(9);
                    break;
                case 'tb3':
                    $('#loaderbar').fadeIn(100);
                    $('#centerContent').load('systemcheck.aspx #syscheck', function() { $('#loaderbar').fadeOut(100); systemcheck(); });
                    break;
                case 'tb2':
                    LoadArticleIntoTab();
                    break;
                case 'tb1':
                    LoadNewFilmsIntoTab();
                    break;
                default:
                    break;
            }

            $(".maintabs  a").each(function() {
                if ($(this).parent().attr('id') !== $thisid) {
                    $(this).parent().css('background-image', 'url(content/img/portal/container-left.gif)');
                    $(this).css('background-image', 'url(content/img/portal/container-right.gif)');
                }
                else {
                    $(this).parent().css('background-image', 'url(content/img/portal/container-left-active.gif)');
                    $(this).css('background-image', 'url(content/img/portal/container-right-active.gif)');
                }
            });
        } catch (r) { alert(r); }
        return false;
    });
    // read cookie to decide initial fontsize
    $(".fontcss").disabled = true;
    $(".fontcss").attr({ href: "" });

    var cf = readCookie("font");
    if (cf) {
        if (cf == "big") {
            var rewt = "";
            if (g_rooturl) rewt = g_rooturl;
            var ssheet = rewt + 'content/css/bigfont.css';
            $(".fontcss").disabled = false;
            $(".fontcss").attr({ href: ssheet });
            $(".ChangeFontSize").text('Normal skrift');
        }
    }

    var netobj = $("#netobj").get(0);
    var player = $("#player").get(0);
    var isNetObjAvailable = false;

    try { isNetObjAvailable = (typeof (netobj.GetDRMSecurityVersion() == "string")); }
    catch (e) { }

    //start playing video when image is clicked
    $("#playerframe").click(function() {
        if (!$('#playercontent').is(':visible')) {
            $('#playercontent').fadeIn(20, function() {
                try {
                    $("#player").css('visibility', 'visible'); //ie "fix"

                    var player = $("#player").get(0);
                    player.uiMode = "full";                    
                    if (isNetObjAvailable) {
                        player.URL = "film/playlist.aspx?teasers=1";
                    } else { player.URL = "film/playlist.aspx?teasers=1&preview=1"; }
                    if (player.controls) {
                        player.controls.play();
                    } else {
                        //if this happens the player is probably still not ready and must be manually started
                    }
                }
                catch (rr) { }
            });
        }
    });
    //toggle big and normal font size
    $(".ChangeFontSize").click(function() {
        if ($(".ChangeFontSize").text() == "Stor skrift") {
            $(".fontcss").disabled = false;
            try {
                var rewt = "";
                if (g_rooturl) rewt = g_rooturl;
                var ssheet = rewt + 'content/css/bigfont.css';
                $(".fontcss").attr({ href: ssheet });
                $(".ChangeFontSize").text('Normal skrift');
                createCookie("font", "big", 7);
            }
            catch (err) {
                //alert('Error:' + err);
            }
        } else {
            $(".fontcss").disabled = true;
            $(".fontcss").attr({ href: "" });
            $(".ChangeFontSize").text('Stor skrift');
            createCookie("font", "normal", 7);
        }
        return false;
    });

    //set up embedding info link
    $('#embedlink').click(function() {
        if ($('#embedcontent').is(':visible')) {
            $('#embedcontent').slideUp(100);
        }
        else {
            $('#embedcontent').slideDown(100);
        }
        return false;
    });
    $('.embedinput').focus(function() {
        $(this).select();
        return false;
    });
});

function debug(msg) {
    if (window.console && window.console.log) {
        window.console.log(msg);
    }
}

function createCookie(name, value, days) {
    var expires="";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

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);
}

var dontCollapse = false;
function DisplayChapters(JSONChap) {
    try {
        if (JSONChap=='') return;
        var chapters = $.evalJSON(JSONChap);
        if (chapters == null || chapters.length == 0) return;
        document.write('<div id="showchap" class="qbtn"><a href="#">Velg kapittel</a></div>');
        document.write("<div id=\"chapterlisting\" class=\"chapters\"><ul id=\"chaplist\">");
        $(chapters).each(function(index, chapter) {
            
            document.write("<li>");
            document.write("<div class=\"chaptertitle\">");
            document.write(index + 1 + ": ");
            document.write(chapter.Title);
            document.write("</div>");
            document.write("<div class=\"chaptertime\">");
            var ChapTime = chapter.TimeOffset.TotalSeconds;
            document.write(FormatTime(ChapTime));
            document.write("</div>");
            document.write("<span class=\"chapteroffset\" style=\"display:none;visibility:hidden;\">");
            document.write(ChapTime);
            document.write("</span>");
            document.write("</li>");
        });
        document.write("</ul></div>");

        $('#chaplist > li:first').addClass('chapterselected');
        $('#showchap a').click(function() { return false; });
        $('#showchap a').hover(function() {
            dontCollapse = true;
            if ($('#chapterlisting').is(':visible')) {
            }
            else {
                $('#chapterlisting').slideDown(100);
                $("#showchap").addClass ("qbtn_on");
            }
            return false;
        }, function() {
        dontCollapse = false;
            setTimeout ("if (!dontCollapse) {$('#chapterlisting').slideUp(100);setTimeout($('#showchap').removeClass ('qbtn_on'),100);}",500);
        });
        $('#chaplist > li').click(function() {
            $('#chaplist > li').removeClass('chapterselected');
            $(this).addClass('chapterselected');
            playerSeek(parseFloat($(".chapterselected > .chapteroffset").text()));
        });
        $('#chaplist').hover(function() { dontCollapse = true; }, function() { dontCollapse = false; setTimeout("if (!dontCollapse) {$('#chapterlisting').slideUp(100);setTimeout($('#showchap').removeClass ('qbtn_on'),100);}", 250); });

    } catch (r) {
        //alert("error:" + r);
    }
}

function FormatTime(secs) {
    var m = parseInt(secs / 60) % 60;
    var t = parseInt((secs / 60) / 60) ;
    var s = parseInt(secs % 60);
    if (t > 0) s = 0;
    var ret = "";
    if (t > 0) ret += t + "t ";
    if (m > 0) ret += m + "m ";
    if (t == 0 )ret += s + "s ";
    return ret;
}
