var selectedPlaylist = null;

function openDefaultNav() {
    renderNewProgramsList();
}

function displayWelcome() {
    showLoadingImageWhite("#content");
    $.get("/portal/site/ieeetv/ieeetv-welcome.html",
    {
        ts: getTimestamp()
    },
    function(data){
        $("#content").html(data);
        trackStats("/portal/site/ieeetv/ieeetv-welcome.html",
            "Welcome Module",
            "/portal/site/ieeetv/ieeetv-welcome.html",
            "");
    });
    displayWelcomeLeaderboardAd();
}

function displayWelcomeLeaderboardAd() {
    $(".banner1-frame").attr("src", "/portal/site/ieeetv/banner1.html");
}

function displayLogin(progId, action, pli, plp) {
    showLoadingImageTransparent("#content");
    var loginURL="/portal/site/ieeetv/protected.html?"
    var thickboxParams = "keepThis=true&TB_iframe=true&height=310&width=510";
    if (progId != null && progId != "") {
        loginURL = loginURL + "uri=%2Fportal%2Fieeetv%2Fviewer.html%3FprogId%3D" + progId;
        if (action != null && action != "") {
            loginURL = loginURL + "%26action%3D" + action;
        }
        if (pli != null && pli != "") {
            loginURL = loginURL + "%26pli%3D" + pli;
        }
        loginURL = loginURL + "&progId=" + progId + "&";
    }
    if (action != null && action != "") {
        loginURL = loginURL + "action=" + action + "&";
    }
    if (pli != null && pli != "") {
        loginURL = loginURL + "pli=" + pli + "&";
    }
    if (plp != null && plp != "") {
        loginURL = loginURL + "plp=" + plp + "&";
    }
    loginURL = loginURL + "ts=" + getTimestamp() + "&" + thickboxParams;
    hideLoadingImageTransparent();

    // darken background
    var msie = false;
    $.each($.browser, function(i, val) {
        if(i=="msie" && val==true){
            msie = true;
        }
    });
    if(msie){
        $("#lightbox_popup").css('opacity',0.8);
        $("#lightbox_popup").show();
    }else{
        $("#lightbox_popup").show().animate({
            opacity: 0.8
        },100);
    }

    tb_show("Login", loginURL, false);
}

function renderNewProgramsList() {
    selectNavTab("nav-tab-new");
    showLoadingImageBlack("#programs-list");
    $.get("/portal/site/ieeetv/new-programs-list.html",
    {
        ts: getTimestamp()
    },
    function(data){
        $("#programs-list").html(data);
        trackStats("/portal/site/ieeetv/new-programs-list.html",
            "New Programs Module",
            "/portal/site/ieeetv/new-programs-list.html",
            "");
    });
}

function renderMostViewedList() {
    selectNavTab("nav-tab-most-viewed");
    showLoadingImageBlack("#programs-list");
    $.get("/portal/site/ieeetv/most-viewed-programs-list.html",
    {
        ts: getTimestamp()
    },
    function(data){
        $("#programs-list").html(data);
        trackStats("/portal/site/ieeetv/most-viewed-programs-list.html",
            "Most Viewed Module",
            "/portal/site/ieeetv/most-viewed-programs-list.html",
            "");
    });
}

function renderFavoritesList() {
    selectNavTab("nav-tab-favorites");
    showLoadingImageBlack("#programs-list");
    $.get("/portal/site/ieeetv/favorite-programs-list.html",
    {
        ts: getTimestamp()
    },
    function(data){
        var error = getError(data);
        if (error != null) {
            displayError(error);
        } else {
            $("#programs-list").html(data);
            trackStats("/portal/site/ieeetv/favorite-programs-list.html",
                "myTv Module",
                "/portal/site/ieeetv/favorite-programs-list.html",
                "");
        }
    });
}

function renderSeriesNavList() {
    selectNavTab("nav-tab-series");
    showLoadingImageBlack("#programs-list");
    $.get("/portal/site/ieeetv/series-nav-list.html",
    {
        ts: getTimestamp()
    },
    function(data){
        $("#programs-list").html(data);
        trackStats("/portal/site/ieeetv/series-nav-list.html",
            "Series Module",
            "/portal/site/ieeetv/series-nav-list.html",
            "");
    });
}

function renderSeriesList(series) {
    showLoadingImageBlack("#programs-list");
    $.get("/portal/site/ieeetv/series-list.html",
    {
        series: series,
        ts: getTimestamp()
    },
    function(data){
        $("#programs-list").html(data);
        trackStats("/portal/site/ieeetv/series-list.html?series=" + series,
            series + " Series Module",
            "/portal/site/ieeetv/series-list.html?series=" + series,
            "");
    });
}

function renderPurchasedList() {
    selectNavTab("nav-tab-purchased");
    showLoadingImageBlack("#programs-list");
    $.get("/portal/site/ieeetv/purchased-programs-list.html",
    {
        ts: getTimestamp()
    },
    function(data){
        var error = getError(data);
        if (error != null) {
            displayError(error);
        } else {
            $("#programs-list").html(data);
            trackStats("/portal/site/ieeetv/purchased-programs-list.html",
                "Purchased Module",
                "/portal/site/ieeetv/purchased-programs-list.html",
                "");
        }
    });
}

function renderPurchasedSubList(pack) {
    removePlayerInIE();
    showLoadingImageWhite("#content");
    $.get("/portal/site/ieeetv/purchased-programs-sublist.html",
    {
        pack: pack,
        ts: getTimestamp()
    },
    function(data){
        var error = getError(data);
        if (error != null) {
            displayError(error);
        } else {
            $("#content").html(data);
            trackStats("/portal/site/ieeetv/purchased-programs-sublist.html?pack=" + pack,
                pack + " Purchased Module",
                "/portal/site/ieeetv/purchased-programs-sublist.html?pack=" + pack,
                "");
        }
    });
}

function renderSearchResultsList() {
    var keyword = $("#search-keyword").val();
    if (keyword == null || keyword == '' || keyword == 'Search Videos') {
        alert('Please provide search criteria');
    } else if (keyword.length <= 2) {
        alert('Search criteria must be longer than 2 characters');
    } else {
        selectNavTab("nav-tab-search");
        showLoadingImageBlack("#programs-list");
        $.get("/portal/site/ieeetv/search-ieeetv.html",
        {
            term: keyword,
            ts: getTimestamp()
        },
        function(data){
            $("#programs-list").html(data);
            trackStats("/portal/site/ieeetv/search-ieeetv.html?term=" + keyword,
                "Search Results Module",
                "/portal/site/ieeetv/search-ieeetv.html?term=" + keyword,
                "");
        });
    }
}

// v Purchased sublist functions v
function switchFolderState(obj) {
    if ($(obj).attr("class") == "expanded") {
        $(obj).removeClass("expanded").addClass("collapsed").next().hide();
    } else {
        $(obj).removeClass("collapsed").addClass("expanded").next().show();
    }
    graph_scroll_start();
    return false;
}

function openFolderToVideo(video) {
    if (video != null && video != "") {
        $("#" + video).addClass("active-presentation");
        $("#" + video).parents("ul:hidden").siblings(".collapsed").each(function() {
            switchFolderState(this);
        });
    }
}
// ^ Purchased sublist functions ^

function selectNavTab(tabId) {
    if (tabId == "nav-tab-search") {
        $("#nav-tab-search").show();
    }
    $("#nav .tabs").children(".item_tab").children("a").each(function() {
        if ($(this).attr("id") == tabId) {
            $(this).addClass("active");
            $("#nav-tab-search").hide();
        } else {
            $(this).removeClass("active");
        }
    });
    // refresh banners on welcome page only
    if ($("#welcome_container").length != 0) {
        refreshBanners();
    }
}

function updatePurchasedTabCount() {
    $.get("/portal/site/ieeetv/purchased-programs-count.html",
    {
        ts: getTimestamp()
    },
    function(data){
        data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        $("#nav-tab-purchased-count").html(data);
    });
}

/**
 * If callingElement is defined and is part of playlist user's current playlist
 * will be updated otherwise it will be reset.
 **/
function playProgram(progId, callingElement) {
    showLoadingImageTransparent("#content");
    //refreshBanners();
    var playlistId = "";
    var playlistPrograms = "";
    if (typeof callingElement != "undefined" && $(callingElement).parents(".thumbs_video_block").length != 0) {
        //playlistId = $(".thumbs_video_block").attr("id");
        playlistId = $(callingElement).parents(".thumbs_video_block").attr("id");
        var programCount = 0;
        $("#" + playlistId + " a").each(function() {
            if (programCount > 0) {
                playlistPrograms = playlistPrograms + ":";
            }
            programCount++;
            playlistPrograms = playlistPrograms + $(this).attr("id").replace("program-icon-", "");
        });
    }
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            //displayError(error, progId);
            processPlayError(error, progId, "play", playlistId, playlistPrograms);
        } else {
            // update user context
            $.get("/portal/site/ieeetv/update-ieeetv.html",
            {
                action: "play",
                progId: progId,
                pli: playlistId,
                plp: playlistPrograms,
                ts: getTimestamp()
            },
            function(data){
                hideLoadingImageTransparent();
                $("#content").html(jdata.player_embed);
                showPlayerInIE();
                if (playlistId != "") {
                    selectedPlaylist = playlistId;
                    processOverlays(progId, playlistId);
                }
                trackStats("/portal/ieeetv/viewer.html?progId=" + progId,
                    jdata.title,
                    jdata.file,
                    "true");
            });
        }
    });
}

function playPurchasedProgram(progId, callingElement) {
    // re-arrange layout
    if ($(".left_col").length != 0) {
        $(".video_title").prependTo(".right_col");
        $(".left_col").removeClass("left_col").addClass("left_col1");
        $(".mid_col").addClass("bg_top_indent");
        $(".right_col").addClass("no_bg");
        $("#ondemand_text").parent().wrap('<div class="right_col_bg"></div>');
    }
    showLoadingImageWhite(".left_col1");
    //refreshBanners();

    // load player
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            displayError(error, progId);
        } else {
            // update user context
            $.get("/portal/site/ieeetv/update-ieeetv.html",
            {
                action: "playPurchased",
                progId: progId,
                ts: getTimestamp()
            },
            function(data){
                $(".left_col1").html(jdata.player_embed);
                showPlayerInIE();
                selectedPlaylist = null;
                trackStats("/portal/ieeetv/viewer.html?progId=" + progId,
                    jdata.title,
                    jdata.file,
                    "true");
            });
        }
    });
}

function playNextUp(progId) {
    //refreshBanners();
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            //displayError(error, progId);
            processPlayError(error, progId, "playNextUp", selectedPlaylist, null);
        } else {
            // update user context + program count
            $.get("/portal/site/ieeetv/update-ieeetv.html",
            {
                action: "playNextUp",
                progId: progId,
                ts: getTimestamp()
            },
            function(data){
                processOverlays(progId, selectedPlaylist);
                trackStats("/portal/ieeetv/next-up.html?progId=" + progId,
                    jdata.title,
                    jdata.file,
                    "true");
            });
        }
    });
}

function playFeatured(progId) {
    //refreshBanners();
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            displayError(error, progId);
        } else {
            // update user context + program count
            $.get("/portal/site/ieeetv/update-ieeetv.html",
            {
                action: "playFeatured",
                progId: progId,
                ts: getTimestamp()
            },
            function(data){
                selectedPlaylist = null;
                clearOverlays();
                trackStats("/portal/ieeetv/featured.html?progId=" + progId,
                    jdata.title,
                    jdata.file,
                    "true");
            });
        }
    });
}

function playRelated(progId) {
    //refreshBanners();
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            displayError(error, progId);
        } else {
            // update user context + program count
            $.get("/portal/site/ieeetv/update-ieeetv.html",
            {
                action: "playRelated",
                progId: progId,
                ts: getTimestamp()
            },
            function(data){
                selectedPlaylist = null;
                clearOverlays();
                trackStats("/portal/ieeetv/related.html?progId=" + progId,
                    jdata.title,
                    jdata.file,
                    "true");
            });
        }
    });
}

function playReplay(progId) {
    //refreshBanners();
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            //displayError(error, progId);
            processPlayError(error, progId, "playReplay", selectedPlaylist, null);
        } else {
            // update program count
            $.get("/portal/site/ieeetv/update-ieeetv.html",
            {
                action: "playReplay",
                progId: progId,
                ts: getTimestamp()
            },
            function(data){
                trackStats("/portal/ieeetv/replay.html?progId=" + progId,
                    jdata.title,
                    jdata.file,
                    "true");
            });
        }
    });
}

function playNowPlaying(progId) {
// do nothing
}

function launchProgram(progId, playlistId) {
    showLoadingImageTransparent("#content");
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            //displayError(error, progId);
            processPlayError(error, progId, "play", playlistId, null);
        } else {
            hideLoadingImageTransparent();
            $("#content").html(jdata.player_embed);
            showPlayerInIE();
            if (playlistId != "") {
                selectedPlaylist = playlistId;
            }
            trackStats("/portal/ieeetv/viewer.html?progId=" + progId,
                jdata.title,
                jdata.file,
                "true");
        }
    });
}

function launchNextUp(progId, playlistId) {
    showLoadingImageTransparent("#content");
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            //displayError(error, progId);
            processPlayError(error, progId, "playNextUp", playlistId, null);
        } else {
            hideLoadingImageTransparent();
            $("#content").html(jdata.player_embed);
            showPlayerInIE();
            if (playlistId != "") {
                selectedPlaylist = playlistId;
            }
            trackStats("/portal/ieeetv/next-up.html?progId=" + progId,
                jdata.title,
                jdata.file,
                "true");
        }
    });
}

function launchReplay(progId, playlistId) {
    showLoadingImageTransparent("#content");
    $.getJSON("/portal/site/ieeetv/ieeetv-player.html",
    {
        progId: progId,
        ts: getTimestamp()
    },
    function(jdata){
        var error = jdata.error;
        if (typeof error != "undefined" && error != null && error != "") {
            //displayError(error, progId);
            processPlayError(error, progId, "playReplay", playlistId, null);
        } else {
            hideLoadingImageTransparent();
            $("#content").html(jdata.player_embed);
            showPlayerInIE();
            if (playlistId != "") {
                selectedPlaylist = playlistId;
            }
            trackStats("/portal/ieeetv/replay.html?progId=" + progId,
                jdata.title,
                jdata.file,
                "true");
        }
    });
}

function launchPurchasedProgram(pack, progId){
    showLoadingImageWhite("#content");
    $.get("/portal/site/ieeetv/purchased-programs-sublist.html",
    {
        pack: pack,
        ts: getTimestamp()
    },
    function(data){
        var error = getError(data);
        if (error != null) {
            displayError(error, progId);
        } else {
            $("#content").html(data);
            playPurchasedProgram(progId);
        }
    });
}

function showPlayerInIE() {
    if (navigator.userAgent.indexOf("MSIE")!=-1 && getInternetExplorerVersion()<7.0)
    {
        $('#ie_ieeetv_player').css({
            'display': 'block'
        });
        if ($('#ie_ieeetv_player').width() == 500)
        {
            $('#ie_ieeetv_player').css({
                'margin-left': '9px'
            });
        }
    }
}

function removePlayerInIE() {
    if (navigator.userAgent.indexOf("MSIE")!=-1 && getInternetExplorerVersion()<7.0)
    {
        $('#ie_ieeetv_player').replaceWith('<div id="ie_ieeetv_player"></div>');
        $('#ie_ieeetv_player').css({
            'display': 'none',
            'top': '68px'
        });
    }
}

function processOverlays(progId, playlistId) {
    if (typeof playlistId != "undefined" &&
        playlistId != null && playlistId != "" &&
        $("#" + playlistId).length != 0) {
        // clear current overlays
        $("#" + playlistId + " a.active").removeClass("active");
        $(".video_thumb_next").remove();
        // set new overlays
        $("#program-icon-" + progId).addClass("active");
        var programs = $("#" + playlistId + " a");

        if (programs.length > 1) {
            var currentIndex = 0;
            programs.each(function() {
                if ($(this).attr("id") == "program-icon-" + progId) {
                    return false; // break
                }
                currentIndex++;
            });
            var nextUpIndex = currentIndex + 1;
            if (nextUpIndex >= programs.length) {
                nextUpIndex = 0;
            }
            $(programs[nextUpIndex]).before('<span class="video_thumb_next">Next up</span>');
        }
    }
}

function clearOverlays() {
    $(".video_thumb a.active").removeClass("active");
    $(".video_thumb_next").remove();
}

// return null if data text does not contain an error code otherwise return
// the error code
function getError(data) {
    var error = null;
    data = data.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    var errorIndexStart = data.indexOf('<error>');
    if (errorIndexStart != -1) {
        error = data.substring(errorIndexStart + 7, data.indexOf('</error>'));
    }
    return error;
}

function processPlayError(type, progId, action, pli, plp) {
    displayError(type, progId, action, pli, plp);
}

function displayError(type, progId, action, pli, plp) {
    removePlayerInIE();
    hideLoadingImageTransparent();
    showLoadingImageWhite("#content");
    var errorPageURL = "/portal/site/ieeetv/error.html?error=" + type;
    if (typeof progId != "undefined" && progId != null && progId != "") {
        errorPageURL = errorPageURL + "&progId=" + progId;
    }
    if (typeof action != "undefined" && action != null && action != "") {
        errorPageURL = errorPageURL + "&action=" + action;
    }
    if (typeof pli != "undefined" && pli != null && pli != "") {
        errorPageURL = errorPageURL + "&pli=" + pli;
    }
    if (typeof plp != "undefined" && plp != null && plp != "") {
        errorPageURL = errorPageURL + "&plp=" + plp;
    }
    errorPageURL = errorPageURL + "&ts=" + getTimestamp();
    $.get(errorPageURL,
        function(data){
            $("#content").html(data);
            trackStats(errorPageURL,
                "Error Module",
                errorPageURL,
                "");
        });
    displayWelcomeLeaderboardAd();
}

function refreshBanners() {
    $(".banner1-frame").attr("src", $(".banner1-frame").attr("src"));
}

function addToFavorites(progId) {
    $.get("/portal/site/ieeetv/update-ieeetv.html",
    {
        action: "addFav",
        progId: progId,
        ts: getTimestamp()
    },
    function(data){
        $("#fav-icon-" + progId + " img").attr("src", "/portal/cms_docs_ieeetv/ieeetv/global/images/icons/myfavorites_minus.gif");
        $("#fav-icon-" + progId + " img").attr("alt", "Remove from myTv");
        $("#fav-icon-" + progId + " img").attr("title", "Remove from myTv");
        $("#fav-icon-" + progId).attr("onclick", "");
        $("#fav-icon-" + progId).unbind();
        $("#fav-icon-" + progId).bind("click", function() {
            removeFromFavorites(progId);
            return false;
        });
        $("#fav-icon-" + progId).removeClass("plus");
        $("#fav-icon-" + progId).addClass("minus");
        $("#nav-tab-fav-count").html(+$("#nav-tab-fav-count").html() + 1);
        trackStats("/portal/site/ieeetv/update-ieeetv.html?action=addFav&progId=" + progId,
            "Add to myTv Action",
            "/portal/site/ieeetv/update-ieeetv.html?action=addFav&progId=" + progId,
            "");
    });
}

function removeFromFavorites(progId) {
    $.get("/portal/site/ieeetv/update-ieeetv.html",
    {
        action: "delFav",
        progId: progId,
        ts: getTimestamp()
    },
    function(data){
        if ($("#program-list-favorites").length != 0) {
            //$("#fav-icon-" + progId).parent().parent("li").remove();
            renderFavoritesList();
        } else {
            $("#fav-icon-" + progId + " img").attr("src", "/portal/cms_docs_ieeetv/ieeetv/global/images/icons/myfavorites_plus.gif");
            $("#fav-icon-" + progId + " img").attr("alt", "Add to myTv");
            $("#fav-icon-" + progId + " img").attr("title", "Add to myTv");
            $("#fav-icon-" + progId).attr("onclick", "");
            $("#fav-icon-" + progId).unbind();
            $("#fav-icon-" + progId).bind("click", function() {
                addToFavorites(progId);
                return false;
            });
            $("#fav-icon-" + progId).removeClass("minus");
            $("#fav-icon-" + progId).addClass("plus");
        }
        $("#nav-tab-fav-count").html($("#nav-tab-fav-count").html() - 1);
        trackStats("/portal/site/ieeetv/update-ieeetv.html?action=delFav&progId=" + progId,
            "Remove from myTv Action",
            "/portal/site/ieeetv/update-ieeetv.html?action=delFav&progId=" + progId,
            "");
    });
}

// selector - element over which the loading image should be displayed and
// centered
function showLoadingImageTransparent(selector) {
    if ($("#loading-image-trans").length == 0) {
        if (selector == "#content") {
            $("#ieeetv_player").css("visibility",'hidden');
        }
        var image = "/portal/cms_docs_ieeetv/ieeetv/global/images/icons/loading_icon_transparent.gif";
        var containerHeight = $(selector).height();
        var containerWidth = $(selector).width();
        var containerOffset = $(selector).offset();
        var top = containerOffset.top + ((containerHeight / 2) - 16);
        var left = containerOffset.left + ((containerWidth / 2) - 16);
        $("body").append("<div id='loading-image-trans' " +
            "style='position:absolute; display:none; z-index:103; height:32px; " +
            "width:32px; top:" + top + "px; left:" + left +"px;'>" +
            "<img src='" + image + "' /></div>");
        $('#loading-image-trans').show();
    }
}

function hideLoadingImageTransparent() {
    $("#loading-image-trans").remove();
}

// selector - element selector of element in which the loading image should be
//            displayed
function showLoadingImageBlack(selector) {
    var image = "/portal/cms_docs_ieeetv/ieeetv/global/images/icons/loading_icon_black.gif";
    showLoadingImage(image, selector);
}

// selector - element selector of element in which the loading image should be
//            displayed
function showLoadingImageWhite(selector) {
    if (selector == "#content") {
        $("#ieeetv_player").css("visibility",'hidden');
    }
    getFlashMovieObject = null;
    var image = "/portal/cms_docs_ieeetv/ieeetv/global/images/icons/loading_icon_white.gif";
    showLoadingImage(image, selector);
}

// selector - element selector of element in which the loading image should be
//            displayed
function showLoadingImage(image, selector) {
    var containerHeight = $(selector).height();
    var paddingTop = (containerHeight / 2) - 16;
    var loadingImg = "<img border='0' alt='Loading...' " +
    "src='" + image + "' " +
    "style='display: block; margin-left: auto; margin-right: auto; padding-top: "
    + paddingTop + "px;'/>";
    $(selector).html(loadingImg);
}

function trackStats(uri, title, file, play) {
    dcsMultiTrack('DCS.dcsuri', uri,
        'WT.ti', title,
        'DCSext.customernumber', $("meta[name='DCSext.customernumber']").attr("content"),
        'DCSext.grade', $("meta[name='DCSext.grade']").attr("content"),
        'DCSext.region', $("meta[name='DCSext.region']").attr("content"),
        'DCSext.section', $("meta[name='DCSext.section']").attr("content"),
        'DCSext.society', $("meta[name='DCSext.society']").attr("content"),
        'DCSext.file', file,
        'DCSext.play', play);
}

function getTimestamp() {
    return new Date().getTime();
}

//************************ v BANNER ADS v ***************************//
function change_banner_src(url)
{
	if (location.href.indexOf("https") === 0)
	{
		url = url.replace(/^http:/i, "https:");
	}
	return url;
}


function check(o) {
    if( (typeof(o) != "undefined") && (o != null) )
	return 1;
    return 0;
}

function fill_banner(s) {
	document.getElementById('banner1').innerHTML = '<iframe id="banner_frame" scrolling="no" width="728" height="90" vspace="0" hspace="0" frameborder="0" allowtransparency="true" marginwidth="0" marginheight="0"></iframe>';
    var doc;
    if(document.all&&!window.opera){
	doc=window.frames['banner_frame'].document;
    }else{
		if(window.opera){
			while(!document.getElementById("banner_frame").contentDocument){};
		};
		doc=document.getElementById("banner_frame").contentDocument;
    }
    if(check(doc)) {
		doc.open();
		doc.writeln(s);
		doc.close();
    }
}

function load_data_into_iframe(url)
{
    //alert("load_data_into_iframe: url: " + url);
    url = change_banner_src(url);
    //alert("load_data_into_iframe after change_banner_src: url: " + url);
    $.ajax({
        url: '/portal/portalproxy.html',
        type: "GET",
        data: "url=" + url,
        success: function(data) {
            //alert(data);
            fill_banner(data);
        }
    });
}

function load_script_into_iframe(script)
{
	fill_banner("<html><body>" + script + "</body></html>");
}

function loadDefaultBanner()
{

	if(typeof(cachebuster) == "undefined"){var cachebuster = Math.floor(Math.random()*10000000000)};
	if(typeof(dcopt) == "undefined"){var dcopt = "dcopt=ist;"} else {var dcopt = ""};
	if(typeof(tile) == "undefined"){var tile = 1} else {tile++};
	var script_src = "http://ad.doubleclick.net/adi/d.site220.tmus/;chan=landing;" + dcopt + ";tile=" + tile + ";sz=728x90;ord=" + cachebuster;
	load_data_into_iframe(script_src);
	//document.getElementById('banner1').innerHTML = "<iframe src="+ script_src +" frameborder=\"0\" scrolling=\"no\" width=\"728\" height=\"90\" marginheight=\"0\" marginwidth=\"0\" allowtransparency=\"true\" ></iframe>";

}

function change_banner_down(url)
{
	if (url.length < 10)
		loadDefaultBanner();
	else
	{
		load_data_into_iframe(url);
	}
}

function replace_img_protocol(html)
{
	if (location.href.indexOf("https") === 0)
	{
		var img_begin_pos = html.indexOf("<img ");
		var str_begin = html.substr(0, img_begin_pos-1);
		var str_last = html.substr(img_begin_pos -1, html.length - img_begin_pos +1);
		var img_end_pos = str_last.indexOf(">");
		var img_str = str_last.substr(0, img_end_pos + 1);
		var end_str = str_last.substr(img_end_pos + 1, str_last.length - img_end_pos + 1);
		return str_begin + img_str.replace(/http:/i, "https:") + end_str;
	}
	else
		return html;
}

function change_banner_down_script(html)
{
	if (html.length < 10)
		loadDefaultBanner();
	else
	{
		load_script_into_iframe(replace_img_protocol(html));
	}
}

function change_banner_down_img(img_src, link, alt)
{
	img_src = change_banner_src(img_src);
	if (link.length < 10)
		loadDefaultBanner();
	else
		document.getElementById('banner1').innerHTML = '<a href="'+link+'" target="_blank"><img src="'+img_src+'" alt="'+alt+'" border=0></a>';
}
//************************ ^ BANNER ADS ^ ***************************//
