﻿$(document).ready(function() {
    var rat = $("input[name=rat]").val();
    var format = $("input[name=format]").val();
    var lang = $("input[name=lang]").val();
    var isSession = $("input[name=isSession]").val();
    var isBroadcasting = $("input[name=isBroadcasting]").val();
    rat = (rat != "" && "ns".indexOf(rat) != -1) ? rat : "unknown";
    format = (format != "" && "flvwmv".indexOf(format) != -1) ? format : "unknown";
    lang = (lang != "" && "dfi".indexOf(lang) != -1) ? lang : "d";
    isSession = (isSession == "true");
    isBroadcasting = (isBroadcasting == "true");
    //console.log(rat, format, lang, isSession, isBroadcasting);

    // show update panel if we expect update loop to run...
    if (isSession && isBroadcasting && rat != "unknown") {
        $(".liveplus-info").show();
    }

    var debug = false;
    var statusUrl = debug ? "_layouts/liveplus/test/status.json" : "/_layouts/liveplus/GetStatus.ashx";
    var geschaeftUrl = debug ? "_layouts/liveplus/test/geschaeft.html" : "/_layouts/liveplus/GetGeschaeft.ashx";
    var biografieUrl = debug ? "_layouts/liveplus/test/biografie.html" : "/_layouts/liveplus/GetBiografie.ashx";

    var currentGeschaeft = "", currentBiografie = "";
    var iframeTimout, $iframe = $("#liveplus-iframe");
    var $geschaeft, $geschaeftActivity, $geschaeftError, $geschaeftInfo;
    var $biografie, $biografieActivity, $biografieError, $biografieInfo;
    var statusBusy = false;

    // load the geschäfts information, and update the container and scroll link contents
    var getGeschaeft = function(url) {
        if ($geschaeft.length > 0) {
            currentGeschaeft = url; // mark as updated
            if (url.indexOf("/test/geschaeft.html") != -1 /*test*/ ||
                url.indexOf("/geschaefte.aspx") != -1) {
                $geschaeftActivity.show();
                jQuery.ajax({
                    type: "GET",
                    url: geschaeftUrl,
                    dataType: "text",
                    data: "lang=" + lang + "&rat=" + rat + "&t=" + new Date().getTime(),
                    success: function(data) {
                        $geschaeftInfo.html(data);
                        geschaeftError(false);
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        geschaeftError(true);
                    }
                });
            } else {
                geschaeftError(true);
            }
        }
    };

    // load the biography information, and update the container and scroll link contents
    var getBiografie = function(url) {

        if ($biografie.length > 0) {
            currentBiografie = url; // mark as updated.

            if (url.indexOf("/test/biografie.html") != -1 /*test*/ ||
                url.indexOf("/biografie.aspx") != -1 ||
                url.indexOf(".admin.ch") != -1) {

                // fetch content of url, but first check whether we have a departement head/ bundesrat.
                // if that is the case, fetch the static html data from the liveplus folder
                // (will be eventually replaced by a parser that fetches data from the department pages)
                var depts = "eda edi efd ejpd evd uvek vbs".split(" ");
                var foundDepartment = false;
                for (var i in depts) {
                    if (url.indexOf(depts[i] + ".admin.ch") != -1) {
                        url = "/" + i18n.lang + "/_layouts/liveplus/biografie/" + depts[i] + ".aspx";
                        foundDepartment = true;
                        break;
                    }
                }
                url = foundDepartment ? url : biografieUrl;
                $biografieActivity.show();
                jQuery.ajax({
                    type: "GET",
                    url: url,
                    dataType: "text",
                    data: "rat=" + rat + "&t=" + new Date().getTime(),
                    success: function(data) {
                        $biografieInfo.html(data);
                        biografieError(false);

                        // extract speaker info, create scroll link.
                        var $speaker = $biografie.find("h1");
                        var $council = $biografie.find("h2.biography-council");
                        var name = $speaker.text() + " - " + $council.text();

                        var $speakerlink = $("#liveplus-speaker");
                        if ($speakerlink.length == 0) alert("speaker link not found!");
                        $speakerlink
						    .show()
						    .find("span").text(name)
						    .click(function() {
						        $iframe.scrollTo($biografie.find("h1:first"), 500, { offset: -20 });
						        return false;
						    });
                    },
                    error: function(xhr, ajaxOptions, thrownError) {
                        biografieError(true);
                    }
                });
            } else {
                biografieError(true);
            }
        }
    };

    var setMeetingActive = function(flag) {
        $(".liveplus-nomeeting-s").css("display", !isBroadcasting && rat == "s" ? "block" : "none");
        $(".liveplus-nomeeting-n").css("display", !isBroadcasting && rat != "s" ? "block" : "none");
        $(".liveplus-info").css("display", flag ? "block" : "none");
        $(".liveplus-player").css("display", flag ? "block" : "none");
    }
    var error = function(flag) {
        geschaeftError(flag);
        biografieError(flag);
    }
    var geschaeftError = function(flag) {
        $geschaeftInfo.css("display", flag ? "none" : "block");
        $geschaeftError.css("display", flag ? "block" : "none");
        $geschaeftActivity.hide();
    }
    var biografieError = function(flag) {
        $biografieInfo.css("display", flag ? "none" : "block");
        $biografieError.css("display", flag ? "block" : "none");
        $biografieActivity.hide();
    }

    // fetch the json data from the status http handler, if the url
    // has changed trigger an update of the data in the respective 
    // content holder in the iframe.
    var getStatus = function() {
        if (statusBusy) return;
        statusBusy = true;
        jQuery.ajax({
            type: "GET",
            url: statusUrl,
            dataType: "json",
            data: "t=" + new Date().getTime(),
            success: function(data) {
                var status = data[rat == "s" ? 1 : 0];
                isBroadcasting = status.State.toLowerCase() == "playing";
                if (isBroadcasting) {
                    setMeetingActive(true);
                    if (status.Biografie != currentBiografie) {
                        getBiografie(status.Biografie);
                    }
                    if (status.Geschaeft != currentGeschaeft) {
                        getGeschaeft(status.Geschaeft);
                    }
                } else {
                    setMeetingActive(false);
                }
                statusBusy = false;
            },
            error: function(xhr, ajaxOptions, thrownError) {
                statusBusy = false;
                error(true);
            }
        });
    };

    // prepare the container elements in the iframe.
    var prepareFrame = function() {
        var content = $iframe.contents().find("#content");
        $geschaeft = content.find("#liveplus-geschaeft");
        $geschaeftActivity = content.find("#liveplus-geschaeft-activity");
        $geschaeftError = content.find("#liveplus-geschaeft-error");
        $geschaeftInfo = content.find("#liveplus-geschaeft-info");
        if ($geschaeft.length + $geschaeftActivity.length + $geschaeftError.length + $geschaeftInfo.length != 4) {
            alert("missing geschäft dom elements!");
        }

        $biografie = content.find("#liveplus-biografie");
        $biografieActivity = content.find("#liveplus-biografie-activity");
        $biografieError = content.find("#liveplus-biografie-error");
        $biografieInfo = content.find("#liveplus-biografie-info");
        if ($biografie.length + $biografieActivity.length + $biografieError.length + $biografieInfo.length != 4) {
            alert("missing biografie dom elements!");
        }

        if (rat != "unknown") {
            // trigger first update, then start the timer to
            // re-load the status each 10 seconds. (event fires
            // the first time after the given delay...)
            getStatus();
            $(document).everyTime(7000, function() { getStatus(); });
        }
    };

    // iframe load function fires too early on ie, poll. else attach load function
    if ($.browser.msie) {
        (function() {
            function frameReady() {
                var body = $("body", $iframe.contents());
                if (body.length != 1) {
                    setTimeout(frameReady, 100);
                    return;
                }
                prepareFrame();
            }
            frameReady();
        })();
    } else {
        $iframe.load(prepareFrame);
    }
});