<% var myth = new Myth(); %>

var statusMessageTimeout = 5000;
var errorMessageTimeout  = 8000;
var gHostName = "<%= myth.GetHostName() %>";

function getHostName() {
    return gHostName;
}

function showHostName() {
    $("#hostname").html(getHostName());
}

function getSetting(hostname, key, defValue) {
    var result = "";

    $.ajaxSetup({ async: false });
    $.getJSON("/Myth/GetSetting",
        { HostName: hostname, Key: key, Default: defValue },
        function(data) {
            result = data.String;
        }).error(function(data) {
            setErrorMessage("<i18n>Unable to retrieve setting.</i18n>");
        });
    $.ajaxSetup({ async: true });

    console.log("getSetting(" + hostname + "," + key + "," + defValue + "):" + result);

    return result;
}

function putSetting(hostname, key, value) {
    var result = 0;

    $.ajaxSetup({ async: false });
    $.post("/Myth/PutSetting",
        { HostName: hostname, Key: key, Value: value },
        function(data) {
            result = 1;
        }).error(function(data) {
            setErrorMessage("<i18n>Unable to save setting.</i18n>");
        });
    $.ajaxSetup({ async: true });

    return result;
}

function installPackage(packageName) {
    var result = 0;

    setStatusMessage("<i18n>Installing</i18n> " + packageName);

    $.ajaxSetup({ async: false });
    $.post("/Config/InstallPackage",
        { package: packageName },
        function(data) {
            if (data.Result == "true") {
                result = 1;
            }
        });
    $.ajaxSetup({ async: true });

    if (result) {
        setStatusMessage("<i18n>Package installed</i18n>");
    } else {
        setErrorMessage("<i18n>Unable to install package.</i18n>");
    }

    return result;
}

function loadDiv(divName, contentURL, jsURL) {

    $("#busyPopup").show();

    divName = "#" + divName;

    var html = $.ajax({
      url: contentURL,
        async: false
     }).responseText;

    $(divName).html(html);

    $("#busyPopup").hide();

    if (jsURL) {
        $.ajaxSetup({ async: false });
        $.getScript(jsURL);
        $.ajaxSetup({ async: true });
    }

    setUIAttributes();
}

function setUIAttributes() {
    $( "input:button").button();
}

var currentContentURL;
var currentJsUrl;

function loadFrontendContent(contentURL) {
    console.log("loadFrontendContent: URL(" + contentURL + ")");
    currentContentURL = contentURL;
    parent.document.getElementById("busyPopup").style.display = "block";
    parent.document.getElementById("content").src = contentURL;
    parent.document.getElementById("busyPopup").style.display = "none";
}

function loadContent(contentURL, jsURL) {
    console.log("loadContent: URL(" + contentURL + ") JSURL(" + jsURL + ")");
    currentContentURL = contentURL;
    currentJsUrl = jsURL;
    loadDiv("content", contentURL, jsURL);
}

function reloadContent() {
    loadContent(currentContentURL, currentJsUrl);
}

function loadSetupJavascript() {
    $.ajaxSetup({ async: false });
    $.getScript("/setup/js/common.js");
    $.ajaxSetup({ async: true });
}

function loadSetupPage(pageName) {
    // hideEditWindow();
    var frame = document.getElementById("content");

    var completeSetupLoad = function() {
        var html = $.ajax({
        url: "/setup/" + pageName + ".html",
            async: false
        }).responseText;

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = "/setup/js/" + pageName + ".js";

        frame = document.getElementById("content");
        frame.contentDocument.getElementById("content").innerHTML = html;
        frame.contentDocument.head.appendChild(script);
        frame.removeEventListener("load", completeSetupLoad);
    };
    frame.addEventListener("load", completeSetupLoad);
    frame.src = "setup/setup_template.html";
}

function loadMiscPage(pageName) {
    var frame = document.getElementById("content");

    var completeMiscLoad = function() {
        var html = $.ajax({
        url: "/misc/" + pageName + ".html",
            async: false
        }).responseText;

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = "/misc/js/" + pageName + ".js";

        frame = document.getElementById("content");
        frame.contentDocument.getElementById("content").innerHTML = html;
        frame.contentDocument.head.appendChild(script);
        frame.removeEventListener("load", completeMiscLoad);
    };
    frame.addEventListener("load", completeMiscLoad);
    frame.src = "misc/misc_template.html";
}

function loadEditWindow(contentURL, jsURL) {
    loadSetupJavascript();
    clearMessages();
    loadDiv("edit", contentURL, jsURL);
    showEditWindow();
}

var lastStatusTimer;
function setStatusMessage(message) {
    if (lastStatusTimer)
        clearTimeout(lastStatusTimer);
    $("#header_status_message").html(message);
    $("#header_status").show();
    setTimeout('$("#header_status").hide("slow"); lastStatusTimer = undefined', statusMessageTimeout);
}

var lastErrorTimer;
function setErrorMessage(message) {
    console.log("ERROR: " + message);
    if (lastErrorTimer)
        clearTimeout(lastErrorTimer);
    $("#header_error_message").html(message);
    $("#header_error").show();
    lastErrorTimer = setTimeout('$("#header_error").hide("slow"); lastErrorTimer = undefined', errorMessageTimeout);
}

function clearMessages() {
    $("#header_status_message").html("");
    $("#header_error_message").html("");
}

function preloadTabs(tabs) {
    var total = tabs.find('.ui-tabs-nav li').length;

    if (total == 0)
        return;

    var currentLoadingTab = 0;
    $tabs.bind('tabsload',function(){
        currentLoadingTab++;
        setUIAttributes();
        if (currentLoadingTab < total)
            $tabs.tabs('load',currentLoadingTab);
        else
            $tabs.unbind('tabsload');
    }).tabs('load',currentLoadingTab);
}

function setupTabs(id, preload) {
    $tabs = $("#" + id).tabs(
        { cache: true,
          spinner: "",
          fx: { opacity: 'toggle', height: 'toggle' } });

    if ((preload == undefined) || (preload == true))
        setTimeout(function(){ preloadTabs($tabs); }, 10);
}

function setupNonAnimatedTabs(id, preload) {
    $tabs = $("#" + id).tabs({ cache: true, spinner: "" });

    if ((preload == undefined) || (preload == true))
        setTimeout(function(){ preloadTabs($tabs); }, 10);
}

function sendMessage() {
    var result  = 0;
    var message = $("#message").val();
    var address = $("#address").val();
    var port    = $("#port").val();
    var timeout = $("#timeout").val();

    $.post("/Myth/SendMessage",
        { Message: message, Address: address, udpPort: port, Timeout: timeout },
        function(data) {
            result = 1;
        }).error(function(data) {
            setErrorMessage("<i18n>Unable to send message.</i18n>");
        });
}

function toggleShowDiv(id) {
    var obj = document.getElementById(id);
    if ( $("#" + id).is(':visible') ) {
        $("#" + id).hide("slow");
    } else {
        $("#" + id).show("slow");
    }
}

function hideConfirm() {
    $("#confirmWindow").hide();
}

function showConfirm(content, functionname, params) {
    $("#confirmWindow").dialog({
        modal: true,
        buttons: {
           '<i18n>Yes</i18n>': function() {
               if (params == null) {
                   functionname();
               }
               else if (params.constructor == Array) {
                   functionname.apply(null, params);
               }
               else {
                   functionname(params);
               }
               $(this).dialog('close');
               },
           '<i18n>No</i18n>': function() { $(this).dialog('close'); }
        }});
    $("#confirmWindow").html(content);
    $("#confirmWindow").show();
    $("#confirmWindow").draggable();
}

function appendMatch(match, divname) {
    var newValue = $("#" + divname).val() + match;
    $("#" + divname).val(newValue);
}

function formatStr() {
    if (arguments.length == 0)
        return "";

    if (arguments.length == 1)
        return arguments[0];

    var result = arguments[0]; 
    for (var i = 1; i < arguments.length; i++) {
        var regexp = '%' + i.toString();
        result = result.replace(regexp, arguments[i]);
    }
    return result;
};


function handleKeyPress(key) {
    if (currentContentURL == "/tv/guide.qsp")
        handleKeyboardShortcutsTV(key);
}

function logout()
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "/setup/logout", true, "nouser", "nopass"); // Page doesn't exist
    xmlhttp.setRequestHeader('X-Myth-Clear-Session', '1');
    xmlhttp.send(null);
    //xmlhttp.abort();
    location.href = '/';
}

function formArray(form)
{
    var formArray = new Array();
    for (i = 0; i < form.elements.length; i++)
    {
        // NOTE: This is a workaround for what seems to be a DOM bug or flaw
        // While all form elements of a disabled fieldset _should_ be also be
        // disabled it appears that the DOM in Chrome, Firefox and perhaps other
        // browsers isn't properly updated to reflect this.
        var isFieldsetDisabled = $(form.elements[i]).closest("fieldset", form).prop("disabled");
        if (!isFieldsetDisabled && form.elements[i].disabled == false)
        {
            formArray[form.elements[i].name] = form.elements[i].value;
        }
    }

    return formArray;
}
