﻿/// <reference path="jQuery-vsdoc.js" />

function GetOuterValues(elem) {
    var theDiv = $("#" + elem);
    var totalWidth = 0; //theDiv.width();
    var padding = parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
    var margin = parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
    var border = parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width

    if (!isNaN(padding))
        totalWidth += padding;

    if (!isNaN(margin))
        totalWidth += margin;

    if (!isNaN(border)) {
        totalWidth += border;
    }

    return totalWidth;
}

function inc(filename) {
    var body = document.getElementsByTagName('body').item(0);
    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    body.appendChild(script)
}

Array.prototype.remove = function(s) {
    for (i = 0; i < this.length; i++)
        if (this[i] == s) {
        this.splice(i, 1);
        return;
    }
}

function fadeText(element, fadeIn, stay, fadeOut) {
    if (fadeIn == null)
        fadeIn = errorFadeInTime;
    if (stay == null)
        stay = errorStayTime;
    if (fadeOut == null)
        fadeOut = errorFadeOutTime;

    $("#" + element).fadeIn(fadeIn).fadeTo(stay, 1).fadeOut(fadeOut);
}

function fadeBorder(element, fadeIn, stay, fadeOut) {
    if (fadeIn == null)
        fadeIn = errorBorderFadeInTime;
    if (stay == null)
        stay = errorBorderStayTime;
    if (fadeOut == null)
        fadeOut = errorBorderFadeOutTime;

    $("#" + element).animate(errorBorderColor, fadeIn).animate(errorBorderColor, stay).animate(noErrorBorderColor, fadeOut);
}

var errorBorderColor = { borderBottomColor: '#ff7777', borderTopColor: '#ff7777', borderLeftColor: '#ff7777', borderRightColor: '#ff7777' };
var noErrorBorderColor = { borderBottomColor: 'white', borderTopColor: 'white', borderLeftColor: 'white', borderRightColor: 'white' };
var errorBorderFadeInTime = 400;
var errorBorderStayTime = 300;
var errorBorderFadeOutTime = 600;
var errorFadeInTime = 500;
var errorStayTime = 2000;
var errorFadeOutTime = 1000;

function GoToRootPage(dummy) {
    // URL: http://whatever.whatever.whatever/whatever/whatever.aspx
    // Development URL: http://localhost:1111/website/whatever/whatever.aspx

    var url = location.href.split('/');
    if (url.length > 2 && url[3].substring(7, 0) == 'website')
        window.location = 'http://' + url[2] + '/' + url[3];
    else
        window.location = 'http://' + url[2];
}

function LogOutBenchmarker() {
    GetJSON(GetRootPath() + "/CommonWebServices.asmx/LogoutBenchmarker", null, false);
    GoToRootPage();
}

function LogOutInstitution() {
    GetJSON(GetRootPath() + "/CommonWebServices.asmx/Logout", null, false);
    //BMTWebServices.CommonWebServices.Logout();
    GoToRootPage();
}

function DefaultErrorFromDB() {
    var header = "Fejl ved læsning/skrivning i databasen";
    var text = "Der opstod desværre en fejl, da der skulle skrives eller læses data i systemet.<br>Fejlen kan være opstået, hvis systemet har logget dig af ved en fejl.<br><br>Prøv igen eller prøv at gå tilbage til forsiden og logge på igen.<br>";
    var icon = "ERROR";
    ShowOKInfoBox(header, text, icon);
}

function ShowErrorBox(message, action, colortheme) {
    var html = GetIconTableHtml("ERROR", message);
    ShowDialog("OKBox", "ok", "Fejl", html, null, null, action, 400, "auto", 0, 0, false, colortheme);
}

function ShowYesNoBox(header, text, icon, yesaction, noaction, colortheme) {
    var html = text;

    if (icon != null)
        html = GetIconTableHtml(icon, text);

    ShowDialog("YESNOBox", "yesno", header, html, yesaction, noaction, null, 400, "auto", 0, 0, false, colortheme);
}

function HideWorkingMessage(name) {
    CloseDialog(name);
}

function ShowWorkingMessage(name, text, colortheme) {
    ShowDialog(name, "working", null, text, null, null, null, "auto", "auto", 0, 0, false, colortheme);
}

function ShowOKInfoBox(header, text, icon, action, colortheme) {
    var html = text;

    if (icon != null)
        html = GetIconTableHtml(icon, text);

    ShowDialog("OKBox", "ok", header, html, null, null, action, 400, "auto", 0, 0, false, colortheme);
}

var DialogZIndex = 3000;
var escapeKeyDialogs = new Array();
var dialogsArray = new Array();

function CloseDialog(name) {
    $('#' + name, top.document).jqmHide();
    $('#' + name, top.document).remove();
    escapeKeyDialogs.remove(name);
    dialogsArray.remove(name);

    if (dialogsArray.length == 0)
        DialogZIndex = 3000;
}

// divName is the name of the div to add the buttons to. Please note: divName will automatically be prefixed "Buttons"
// (this is because, then it can be used in dialogs by just sending the dialog-name!)
function AddButtons(divName, btnArray, justify) {
    var buttonHTML = '';
    var foundHtmlUnderBtn = false;
    if (btnArray != null) {

        buttonHTML += "<table border='0' id='Table" + divName + "Buttons' cellpadding='0' cellspacing='0'>";
        buttonHTML += "<tr>";

        for (i = 0; i < btnArray.length; i++) {
            buttonHTML += "<td style='padding-left:8px;padding-right:8px;'>";
            buttonHTML += '        <input type="button" class="button" value="' + btnArray[i].label + '" onclick="' + btnArray[i].click + '"';

            if (btnArray[i].onmouseover != null)
                buttonHTML += 'onmouseover="' + btnArray[i].onmouseover + '"';

            if (btnArray[i].onmouseout != null)
                buttonHTML += 'onmouseout="' + btnArray[i].onmouseout + '"';

            buttonHTML += " />";

            if (btnArray[i].htmlUnderBtn != null)
                foundHtmlUnderBtn = true;

            buttonHTML += "</td>";
        }

        buttonHTML += "</tr>";

        if (foundHtmlUnderBtn) {
            buttonHTML += "<tr>";

            for (i = 0; i < btnArray.length; i++) {
                buttonHTML += "<td>";
                if (btnArray[i].htmlUnderBtn != null)
                    buttonHTML += btnArray[i].htmlUnderBtn;
                else
                    buttonHTML += "&nbsp;";

                buttonHTML += "</td>";
            }
            buttonHTML += "</tr>";
        }

        buttonHTML += "</table>";

        $("#Buttons" + divName).html(buttonHTML);

        if (justify != null) {
            // Centering
            if (justify == "right") {
                $("#Table" + divName + "Buttons").css("margin-left", "auto");
                $("#Table" + divName + "Buttons").css("margin-right", "0px");
            }
            else if (justify == "left") {
                $("#Table" + divName + "Buttons").css("margin-left", "0px");
                $("#Table" + divName + "Buttons").css("margin-right", "auto");
            }
            else {
                $("#Table" + divName + "Buttons").css("margin-left", "auto");
                $("#Table" + divName + "Buttons").css("margin-right", "auto");
            }
        }
    }
}

function ShowDialog(name, type, title, content, callbackYes, callbackNo, callbackOKClose, width, height, maxWidth, maxHeight, rightjustifyButtons, colortheme, closeWithEscape, btnArray, centerVertically) {

    for (i = 0; i < dialogsArray.length; i++)
        if (dialogsArray[i] == name)
        return;

    var btnYesLabel = "  Ja  ";
    var btnNoLabel = "  Nej  ";
    var btnOKCloseLabel = "  OK  ";
    var btnJustify = "center";

    DialogZIndex += 50;

    dialogsArray[dialogsArray.length] = name;

    if (type == "close")
        btnOKCloseLabel = "  Luk  ";

    if (rightjustifyButtons == true)
        btnJustify = "right";

    var dialogBorderCSS;
    var dialogTitleCSS;
    var btnCSS;
    var workingCSS;
    if (colortheme == null) {
        dialogBorderCSS = 'jqmDialogWindowDefaultColors';
        dialogTitleCSS = 'jqmDialogTitleDefaultColors';
        btnCSS = 'button';
        workingCSS = 'jqmDialogWorking';
    }
    else if (colortheme == "termometeret") {
        dialogBorderCSS = 'jqmDialogWindowTermometeretColors';
        dialogTitleCSS = 'jqmDialogTitleTermometeretColors';
        btnCSS = 'jqmDialogButtonTermometeret';
        workingCSS = 'jqmDialogWorkingTermometeret';
    }

    var DialogHTML = '';

    if (type == "working") {
        DialogHTML += '<div id="' + name + '" class="jqmDialog">';
        DialogHTML += '  <div class="' + dialogBorderCSS + ' jqmDialogWindow">';
        DialogHTML += '    <div id="Dialog' + name + 'Window">';
        DialogHTML += '      <center>';
        DialogHTML += '        <br>';
        DialogHTML += '        <DIV id="Dialog' + name + 'Content" style="height:auto;padding:7px;overflow:auto;">';
        DialogHTML += '          &nbsp;';
        DialogHTML += '        </DIV>';
        DialogHTML += '        <br>';
        DialogHTML += '        <div class="' + workingCSS + '"></div>';
        DialogHTML += '        <br>';
        DialogHTML += '      </center>';
        DialogHTML += '    </div>';
        DialogHTML += '  </div>';
        DialogHTML += '</div>';
    }
    else {
        DialogHTML += '<div id="' + name + '" class="jqmDialog" style="width:100%; height:100%;">';
        DialogHTML += '  <div id="inner' + name + '" class="' + dialogBorderCSS + ' jqmDialogWindow">';
        DialogHTML += '    <div id="Dialog' + name + 'Window" style="height:100%;width:100%;">';
        DialogHTML += '      <DIV class="ui-layout-north" style="background-color:#FFFFFF;">  ';
        DialogHTML += '        <div id="DialogTitle" class="' + dialogTitleCSS + ' jqmDialogTitle">';
        DialogHTML += '          Overskrift';
        DialogHTML += '        </div>';
        DialogHTML += '      </DIV>';
        DialogHTML += '      <DIV class="ui-layout-center" id="Dialog' + name + 'Content" style="height:auto;padding:7px;overflow:auto;">';
        DialogHTML += '      &nbsp;';
        DialogHTML += '      </DIV>';
        DialogHTML += '      <DIV id="Buttons' + name + '" class="ui-layout-south" style="padding:5px;text-align:' + btnJustify + ';">';
        if (btnArray != null) {
            for (i = 0; i < btnArray.length; i++) {
                DialogHTML += '        <input type="button" class="' + btnCSS + '" value="' + btnArray[i].label + '" onclick="' + btnArray[i].click + '" />';

                if (btnArray.length - 1 != i)
                    DialogHTML += "&nbsp;&nbsp;&nbsp;";
            }
        }
        else {
            DialogHTML += '        <input type="button" id="YesButton" class="' + btnCSS + '" value="' + btnYesLabel + '" />';
            DialogHTML += '        <input type="button" id="NoButton" class="' + btnCSS + '" value="' + btnNoLabel + '" />';
            DialogHTML += '        <input type="button" id="OKCloseButton" class="' + btnCSS + '" value="' + btnOKCloseLabel + '" />';
        }
        DialogHTML += '      </DIV>';
        DialogHTML += '    </div>';
        DialogHTML += '  </div>';
        DialogHTML += '</div>';
    }

    $("body", top.document).append(DialogHTML);
    $('#' + name, top.document).css("z-index", DialogZIndex);

    $('#' + name, top.document).jqm({ overlay: 25, modal: true, trigger: false });

    var preferedZIndex = DialogZIndex + 2;
    if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6")
        preferedZIndex = 50000; // Muligvis noedvendig for at popup i IE6 virker!

    $('#' + name, top.document)
    .jqmShow()
    .find('#Dialog' + name + 'Content')
        .html(content)
    .end();

    if (type != "working")
        $('#' + name, top.document).find('#DialogTitle').html(title).end();

    if (width != "auto") {
        $('#inner' + name, top.document).width(width);
        if (parseInt($('#inner' + name, top.document).width()) > maxWidth && maxWidth != 0) {
            $('#inner' + name, top.document).width(maxWidth + "px");
        }
    }
    if (height != "auto") {
        $('#inner' + name, top.document).height(height);
        if (parseInt($('#inner' + name, top.document).height()) > maxHeight && maxHeight != 0) {
            $('#inner' + name, top.document).height(maxHeight + "px");
        }
    }

    //var currentHeight = $('#' + name + ' .jqmDialogWindow').height();
    //var currentWidth = $('#' + name + ' .jqmDialogWindow').width();

    var currentHeight = $('#inner' + name, top.document).height();
    var currentWidth = $('#inner' + name, top.document).width();

    if (width == "auto") {
        $('#inner' + name, top.document).css("width", currentWidth);
        $('#inner' + name, top.document).css("max-width", currentWidth);
    }
    if (height == "auto") {
        $('#inner' + name, top.document).css("height", currentHeight);
        $('#inner' + name, top.document).css("max-height", currentHeight);
    }

    if (type != "working") {
        $('#' + name + " #Dialog" + name + "Window").layout({ spacing_open: 0 });
    }

    var browserWindowWidth = $(window, top.document).width();
    var browserWindowHeight = $(window, top.document).height();
    var dialogWidth = $('#' + name, top.document).width();
    var dialogHeight = $('#' + name, top.document).height();

    $('#' + name, top.document).css("left", (browserWindowWidth / 2) - (dialogWidth / 2));

    // Centrer vindue!!!
    if (centerVertically) {
        var topPosition = (browserWindowHeight / 2.0 - currentHeight / 2.0) + 'px';
        $('#' + name).addClass("modalCenterVertically");
        $('#' + name).css("top", topPosition);
    }

    $('#' + name + ' .ui-layout-center', top.document).css("z-index", preferedZIndex);
    $('#' + name + ' .ui-layout-north', top.document).css("z-index", preferedZIndex);
    $('#' + name + ' .ui-layout-south', top.document).css("z-index", preferedZIndex);

    if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6") {
        $('#' + name, top.document).css("z-index", 50000);
        $('#' + name, top.document).css("position", "absolute");
        $('#' + name, top.document).css("top", "100px");
        $('#' + name, top.document).css("left", "10px");
        $.scrollTo($('body', top.document), 0);
    }

    if (type == "yesno") {
        $('#' + name, top.document)
            .find('#YesButton')
                .show()
            .end()
            .find('#NoButton')
                .show()
            .end()
            .find('#OKCloseButton')
                .hide()
            .end();
    }
    else if (type == "ok" || type == "close") {
        $('#' + name, top.document)
            .find('#YesButton')
                .hide()
            .end()
            .find('#NoButton')
                .hide()
            .end()
            .find('#OKCloseButton')
                .show()
            .end();
    }

    if (type != "working" && type != null) {
        $('#' + name, top.document).find(':button:visible')
          .click(function() {

              if (this.value == btnYesLabel || this.value == btnNoLabel || this.value == btnOKCloseLabel)
                  CloseDialog(name);

              if (this.value == btnYesLabel && typeof callbackYes == 'function')
                  callbackYes();
              else if (this.value == btnYesLabel && typeof callbackYes == 'string')
                  eval(callbackYes);
              else if (this.value == btnNoLabel && typeof callbackNo == 'function')
                  callbackNo();
              else if (this.value == btnNoLabel && typeof callbackNo == 'string')
                  eval(callbackNo);
              else if (this.value == btnOKCloseLabel && typeof callbackOKClose == 'function')
                  callbackOKClose();
              else if (this.value == btnOKCloseLabel && typeof callbackOKClose == 'string')
                  eval(callbackOKClose);
          });
    }

    if (type == "yesno" || type == "close" || closeWithEscape) {
        escapeKeyDialogs[escapeKeyDialogs.length] = name;
    }
}

$(document).keydown(function(e) {
    if (e.which == 27) {
        //$(document).unbind("keydown");
        if (escapeKeyDialogs.length > 0) {
            if (dialogsArray[dialogsArray.length - 1] == escapeKeyDialogs[escapeKeyDialogs.length - 1]) {
                var name = dialogsArray[dialogsArray.length - 1];
                CloseDialog(name);
            }
        }
    }
});

function GetIconTableHtml(icon, message) {
    var iconPath = GetIconPath(icon);

    var html = '';

    html += '<table border="0">';
    html += '    <tr>';
    html += '        <td valign="top">';
    html += '            <div style="margin-right: 10px;">';
    html += '              ' + iconPath;
    html += '            </div>';
    html += '        </td>';
    html += '        <td valign="top">';
    html += '            <p>';
    html += '                ' + message;
    html += '            </p>';
    html += '        </td>';
    html += '    </tr>';
    html += '</table>';

    return html;
}

function GetIconPath(icon) {
    var imagePath = "<img src=\"" + GetRootPath() + "/images/";

    if (icon == "INFORMATION")
        imagePath += "info.jpg\">";
    else if (icon == "ERROR")
        imagePath += "error.jpg\">";
    else if (icon == "THANKYOU")
        imagePath += "thankyou.jpg\">";
    else if (icon == "QUESTION")
        imagePath += "questionmark.jpg\">";
    else if (icon == "HAPPY")
        imagePath += "happy.gif\">";
    else if (icon != null)
        imagePath = icon;

    return imagePath;
}

function GetSyncPage(page) {
    var result = '';

    $.ajax({
        url: page,
        async: false,
        success: function(html) {
            result = html;
        },
        error: function(request, errorType, errorThrown) {
            alert("fejl: " + errorType + " :: " + errorThrown);
        }
    });

    return result;
}

// Gets data async. The json-parameter will be sent to the webmethod, if it's
// not null.
function GetAsyncJSON(service, jsonData, callback) {
    var jsonData;

    if (jsonData == null)
        jsonData = "{}";

    $.ajax({
        type: "POST",
        url: service,
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function(msg) {
            callback(msg.d);
        },
        error: function(request, errorType, errorThrown) {
            alert("fejl: " + errorType + " :: " + errorThrown);
        }
    });
}

// Gets data async. Will convert SIMPLE javascript object to JSON before calling
// services. Please note: Will not convert arrays etc. to JSON, that can
// be understood by the webmethod!
function GetAsyncJSOBJ(service, object, callback) {
    var jsonData;

    if (object == null)
        jsonData = "{}";
    else
        jsonData = JSON.stringify(object);

    $.ajax({
        type: "POST",
        url: service,
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        success: function(msg) {
            callback(msg.d);
        },
        error: function(request, errorType, errorThrown) {
            alert("fejl: " + errorType + " :: " + errorThrown);
        }
    });
}

function GetJSON(service, dataval, asyncval) {
    if (dataval == null || dataval == '')
        dataval = "{}";

    var result = null;

    $.ajax({
        type: "POST",
        url: service,
        data: dataval,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: asyncval,
        success: function(msg) {
            result = msg.d;
        },
        error: function(request, errorType, errorThrown) {
            alert("fejl: " + errorType + " :: " + errorThrown);
        }
    });

    return result;
}

function confirm(type, title, msg, icon, callbackYes, callbackNo, callbackOK) {

    var imagePath = "<img src=\"" + GetRootPath() + "/images/";

    if (icon == "INFORMATION")
        imagePath += "info.jpg\">";
    else if (icon == "ERROR")
        imagePath += "error.jpg\">";
    else if (icon == "THANKYOU")
        imagePath += "thankyou.jpg\">";
    else if (icon == "QUESTION")
        imagePath += "questionmark.jpg\">";
    else if (icon != null)
        imagePath = icon;

    $('#confirm')
    .jqmShow()
    .find('p.jqmConfirmMsg')
      .html(msg)
    .end()
    .find('p.jqmTitleMsg')
      .html(title)
    .end()
      .find('div.jqmIcon').html(imagePath)
    .end();

    if (type == "yesno") {
        $('#confirm')
            .find('#YesButton')
                .show()
            .end()
            .find('#NoButton')
                .show()
            .end()
            .find('#OKButton')
                .hide()
            .end();
    }
    else if (type == "ok") {
        $('#confirm')
            .find('#YesButton')
                .hide()
            .end()
            .find('#NoButton')
                .hide()
            .end()
            .find('#OKButton')
                .show()
            .end();
    }

    $('#confirm').find(':button:visible')
      .click(function() {

          $('#confirm').jqmHide();
          $(document).unbind("keydown");

          if (this.value == '  Ja  ' && typeof callbackYes == 'function')
              callbackYes();
          else if (this.value == '  Ja  ' && typeof callbackYes == 'string')
              eval(callbackYes);
          else if (this.value == ' Nej ' && typeof callbackNo == 'function')
              callbackNo();
          else if (this.value == " Nej " && typeof callbackNo == 'string')
              eval(callbackNo);
          else if (this.value == '  OK  ' && typeof callbackOK == 'function')
              callbackOK();
          else if (this.value == "  OK  " && typeof callbackOK == 'string')
              eval(callbackOK);
      });

    if (type == "yesno") {
        $(document).keydown(function(e) {
            if (e.which == 27) {
                $(document).unbind("keydown");
                $('#confirm').jqmHide();
            }
        });
    }
}



/*function EndRequestHandler(sender, args)
{
//document.getElementById('ctl00_PleaseWaitImage').style.display = 'none';
if (args.get_error() == undefined)
{
//CTRL = ALT = SHIFT = null;
CHAR_CODE = -1;
HandleMessages();
UpdateRow();
}
else
alert("There was an error" + args.get_error().message);
}*/

function PutAccordion(location, title, text, defaultClosed) {
    var str = '';

    str += "<div class='accordionhead'>";
    str += "<table border=0>";
    str += "<tr>";
    str += "<td valign='top'>";
    str += "<img id='icon' src='" + GetRootPath() + "/images/expand.gif' />";
    str += "</td>";
    str += "<td>";
    str += "<b>" + title + "</b>";
    str += "</td>";
    str += "</tr>";
    str += "</table>";
    str += "</div>";

    if (defaultClosed == true || defaultClosed == null)
        str += "<div class='accordionbody' style='display:none'>";
    else
        str += "<div class='accordionbody'>";

    str += text;
    str += "</div>";

    // If we cannot find the div (location) on the main site, we'll look
    // if it exists in an iframe on the site called columnframe (used by the frontpages).
    if (document.getElementById(location))
        $('#' + location).html(str);
    else {
        var iframe = document.getElementById('columnframe').contentWindow.document;
        $(iframe.getElementById(location)).html(str);
    }
}

function prepareAccordions() {
    // Prepare accordions
    $('.accordionhead').click(function() {
        $(this).next().toggle('fast');
        var currentImg = $(this).find('#icon').attr("src");
        if (currentImg != null) {
            if (currentImg.indexOf('expand') != -1)
                $(this).find('#icon').attr("src", "images/collapse.gif");
            else
                $(this).find('#icon').attr("src", "images/expand.gif");
        }
        return false;
    }) //.next().hide();  // Will close all accordions as default

    // Also check if there's accordions in an iframe...
    var iframe = document.getElementById('columnframe');
    if (iframe) {
        iframe = iframe.contentWindow.document;
        $(iframe).find('.accordionhead').click(function() {
            $(this).next().toggle('fast');
            var currentImg = $(this).find('#icon').attr("src");
            if (currentImg != null) {
                if (currentImg.indexOf('expand') != -1)
                    $(this).find('#icon').attr("src", "images/collapse.gif");
                else
                    $(this).find('#icon').attr("src", "images/expand.gif");
            }
            return false;
        });
    }
}

$().ready(function() {
    //Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

    if (window["HandleMessages"] != null)
        HandleMessages();

    if (window["UpdateRow"] != null)
        UpdateRow();

    if (typeof ("placeFooterText") == "function")
        placeFooterText();

    // Prepare confirm box
    $('#confirm').jqm({ overlay: 25, modal: true, trigger: false });
    $('#confirm .jqmConfirmWindow').css("height", "auto");

    // trigger a confirm whenever links of class alert are pressed.
    //$('a.confirm').click(function() { 
    //  confirm('er du sikker? !',this.href); 
    //  return false;
    //});
});


var pleaseWaitCounter = 0;

function showPleaseWait() {
    pleaseWaitCounter++;
    if (document.getElementById('PleaseWaitDiv') != null)
        document.getElementById('ImagePleaseWait').style.display = "inline";
}

function hidePleaseWait() {
    if (pleaseWaitCounter > 0) {
        pleaseWaitCounter--;
        if (pleaseWaitCounter == 0 && document.getElementById('PleaseWaitDiv') != null)
            document.getElementById('ImagePleaseWait').style.display = "none";
    }
}

function getMarkedCheckboxIDs(tablename, prefix) {
    var ids = new Array();

    $("#" + tablename + " :checkbox:[id^='" + prefix + "']:checked").each(function() {
        ids[ids.length] = $(this).attr("id").split('_')[1];
    });

    return ids;
}

function LastDayOfMonth(Year, Month) {
    return (new Date((new Date(Year, Month + 1, 1)) - 1)).getDate();
}

function addHoverEffect(tablename) {
    $('#' + tablename + ' tbody tr').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });
}

function addClickMarkCheckbox(tablename, prefix, callbackChecked, callbackUnchecked) {
    $('#' + tablename + ' tbody tr').click(function(event) {
        if (event.target.type !== 'checkbox') {
            $(':checkbox', this).trigger('click');
        }
        else {
            var checked = $(this).find("#[id*='" + prefix + "']").attr('checked');

            if (checked) {
                $(this).addClass('selected');
                if (typeof (callbackChecked) === "function") {
                    callbackChecked();
                }
            }
            else {
                $(this).removeClass('selected');
                if (typeof (callbackUnchecked) === "function") {
                    callbackUnchecked();
                }

            }
        }
    });
}

Array.prototype.contains = function(value) {
    for (arrI = 0; arrI < this.length; arrI++)
        if (this[arrI] == value)
        return arrI;

    return -1;
}

function textCounter(field, maxlimit, countfield) {
    if (field.value.length > maxlimit) // if too long... trim it!
    {
        field.value = field.value.substring(0, maxlimit);
        if (countfield != null)
            document.getElementById(countfield).innerHTML = '0';
    }

    // otherwise, update 'characters left' counter
    else if (countfield != null)
        document.getElementById(countfield).innerHTML = maxlimit - field.value.length;
}


this.tooltip = function() {
    /* CONFIG */
    xOffset = 10;
    yOffset = 20;
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result		
    /* END CONFIG */
    $("span.tooltip").hover(function(e) {
        this.t = this.title;
        this.title = "";
        $("body").append("<p id='tooltip'>" + this.t + "</p>");
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function() {
	    this.title = this.t;
	    $("#tooltip").remove();
	});
    $("span.tooltip").mousemove(function(e) {
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
    });
};

function GetRootPath() {
    // URL: http://whatever.whatever.whatever/whatever/whatever.aspx
    // Development URL: http://localhost:1111/website/whatever/whatever.aspx
    var url = location.href.split('/');
    if (url.length > 2 && url[3].substring(7, 0) == 'website')
        return "/website";

    return "";
}

function PrintManual(guideToPrint) {
    if (guideToPrint == 'questionnaire')
        window.open(GetRootPath() + '/vejledning_til_fritidshjem_boernehavens_4_til_6.pdf', '', '');
    else if (guideToPrint == 'benchmarker')
        window.open(GetRootPath() + '/vejledning_til_benchmarking.pdf', '', '');
    else if (guideToPrint == 'dagplejehjem')
        window.open(GetRootPath() + '/vejledning_til_dagplejen.pdf', '', '');
    else if (guideToPrint == 'mindstedt')
        window.open(GetRootPath() + '/vejledning_til_vuggestue_og_boernehave.pdf', '', '');
}

function SendSupport() {

    var errors = 0;
    if (!RequiredField('SupportNameTextBox', true, true, 'SupportNameBorder', 'border', 255, 255, 255, 255, 0, 0))
        errors++;

    if (!RequiredEmail('SupportEmailTextBox', true, true, 'SupportEmailBorder', 'border', 255, 255, 255, 255, 0, 0))
        errors++;

    if (errors == 0) {
        var supportObj = new Object;

        supportObj.name = document.getElementById('SupportNameTextBox').value;
        supportObj.email = document.getElementById('SupportEmailTextBox').value;
        supportObj.institution = document.getElementById('SupportInstitutionTextBox').value;
        supportObj.text = document.getElementById('SupportTextArea').value;

        showPleaseWait();

        GetAsyncJSOBJ("CommonWebServices.asmx/SendSupport", supportObj, function(json) {
            hidePleaseWait();
            CloseDialog('SupportDialog');

            if (json == "okay") {
                var header = "Tak for din henvendelse";
                var text = "Din henvendelse er nu sendt til DCUM. Vi vil besvare din henvendelse så hurtigt som muligt.";
                ShowOKInfoBox(header, text, "INFORMATION");

                return;
            }

            var header = "Fejl ved supportafsending";
            var text = "Der opstod desværre en fejl, da din henvendelse skulle sendes til os.<br><br>";
            text += "Du er velkommen til at kontakte os direkte på mail: <a href=\"mailto:bm-termometeret@dcum.dk\">bm-termometeret@dcum.dk</a>";

            ShowOKInfoBox(header, text, "ERROR");
        });
    }
}

function SendFeedback() {

    var errors = 0;

    if (!RequiredField('FeedbackNameTextBox', true, true, 'FeedbackNameBorder', 'border', 255, 255, 255, 255, 0, 0))
        errors++;

    if (!RequiredEmail('FeedbackEmailTextBox', true, true, 'FeedbackEmailBorder', 'border', 255, 255, 255, 255, 0, 0))
        errors++;

    if (errors == 0) {
        var feedbackObj = new Object;

        feedbackObj.name = document.getElementById('FeedbackNameTextBox').value;
        feedbackObj.email = document.getElementById('FeedbackEmailTextBox').value;
        feedbackObj.institution = document.getElementById('FeedbackInstitutionTextBox').value;
        feedbackObj.text = document.getElementById('FeedbackTextArea').value;

        showPleaseWait();

        GetAsyncJSOBJ("CommonWebServices.asmx/SendFeedback", feedbackObj, function(json) {
            hidePleaseWait();
            CloseDialog('FeedbackDialog');

            if (json == "okay") {
                var header = "Tak for din feedback";
                var text = "Din feedback er nu sendt til DCUM. Du vil ikke få svar fra os på din feedback, med mindre vi har brug for yderligere oplysninger fra dig.";
                ShowOKInfoBox(header, text, "INFORMATION");

                return;
            }

            var header = "Fejl ved afsending af feedback";
            var text = "Der opstod desværre en fejl, da din feedback skulle sendes til os.<br><br>";
            text += "Du er velkommen til at kontakte os direkte på mail: <a href=\"mailto:bm-termometeret@dcum.dk\">bm-termometeret@dcum.dk</a>";

            ShowOKInfoBox(header, text, "ERROR");
        });
    }
}

// ---- DIALOGS ----

function ShowChooseManualDialog() {
    ShowDialog("GuideFrontpageDialog", "close", "Vejledninger", "Henter data...", null, null, null, 650, 200, 0, 0, "true");
    $("#GuideFrontpageDialog #DialogGuideFrontpageDialogContent").load(GetRootPath() + "/dialogs/guideFrontpage.html");
}

function ShowAboutBMT() {
    //var result = GetJSON("ManualWebServices.asmx/GetAboutBMT", null, false);
    //alert(result);

    ShowDialog("AboutDialog", "close", "Om Børnemiljøtermometeret", "Henter data...", null, null, null, 550, 400, 0, 0, "true");
    $("#" + "AboutDialog #DialogAboutDialogContent").load(GetRootPath() + "/dialogs/about.html");
}

function doResizeJQueryTabs() {
    if ($("#[id^='fragment']").length > 0) {

        var height = $("#ContentDivCenter").height();

        var maxTop = 0;
        $("#[id^='fragment']").each(function() {
            maxTop = Math.max($(this).position().top, maxTop);
        });

        height -= maxTop * 2;

        $("#[id^='fragment']").height(height + "px");
    }

    if (typeof (setHeightOfResultPopup) == "function")
        setHeightOfResultPopup();

    doResizeLayoutDivs();
}

function doResizeLayoutDivs() {
    // Each screen can add DIVs, that must be layoutet again
    // if window is resized.
    // Here we handle all those DIVs:
    $('.LayoutDivResize').each(function() {
        $(this).layout({ spacing_open: 0 });
    });
}

function doResizeCenteredModals() {
    // All modal windows, that must center vertically
    // will be re-centered, if window is resized!
    var browserWindowHeight = $(window, top.document).height();
    //alert(browserWindowHeight);
    $('.modalCenterVertically').each(function() {
        var name = $(this).attr("id");
        var currentHeight = $('#inner' + name, top.document).height();
        var topPosition = (browserWindowHeight / 2.0 - currentHeight / 2.0) + 'px';
        //alert("found one! name: " + name);
        $(this).css("top", topPosition);
    });
}

// $(window).resize(...) is not used, as it's run as soon
// as you do the resize - and not after it's finished.
// So when you call height() etc, it'll give you the height
// before the resize!
var resizeTimer = null;
var resizeCenteredModalsTimer = null;

//$(window).bind('resize', function() {
$(window).resize(function() {

    doResizeJQueryTabs();
    doResizeCenteredModals();
    //alert("please wait...");
    if (typeof (doResizeResultDialogDivs) != "undefined")
        doResizeResultDialogDivs();

    if (resizeTimer)
        clearTimeout(resizeTimer);

    resizeTimer = setTimeout(doResizeJQueryTabs, 1000);

    //if (resizeCenteredModalsTimer)
    //    clearTimeout(resizeCenteredModalsTimer);

    //resizeCenteredModalsTimer = setTimeout(doResizeCenteredModals, 1000);
});

// TODO: Skal fjernes, naar den ikke laengere bruges af diverse funktioner!
var PlaceHolder = "ctl00_MainContentPlaceHolder_";

// TODO: Skal fjernes, naar den ikke laengere bliver brugt! (Fremover skal ShowDialog bruges, som
// selv haandterer z-index automatisk!)
function moveZIndex(popup, newZIndex) {
    // popup must be the first part of the modulpopupextender window (excl. "popup" or "bhvr" etc)

    var currentZIndex;

    var prefix = '';
    var mprefix = '';

    // search for element
    if (document.getElementById(PlaceHolder + popup + 'Popup') != null)
        prefix = PlaceHolder;
    else if (document.getElementById('ctl00_' + popup + 'Popup') != null)
        prefix = 'ctl00_';

    if (prefix == '')
        return false;

    if (document.getElementById(popup + 'Bhvr_backgroundElement') != null)
        mprefix = '-';
    else if (document.getElementById('Modal' + popup + 'Bhvr_backgroundElement') != null)
        mprefix = 'Modal';

    if (mprefix == '')
        return false;

    if (mprefix == '-')
        mprefix = '';

    //currentZIndex = document.getElementById(prefix + popup + 'Popup').style.zIndex;
    document.getElementById(prefix + popup + 'Popup').style.zIndex = newZIndex;

    //currentZIndex = document.getElementById(popup + 'Bhvr_backgroundElement').style.zIndex;
    document.getElementById(mprefix + popup + 'Bhvr_backgroundElement').style.zIndex = newZIndex - 1;
}


String.prototype.trim = function() { return this.replace(/^\s*/, "").replace(/\s*$/, ""); }

function SplitCSV(str) {
    // 360,'Her er,, en "forfærdlig" udgave'', af <br><br> _''et''_spørgsmål'
    var list = new Array();
    var work = '';
    var separator = ',';
    var textSeparator = "'";

    for (var i = 0; i < str.length; i++) {
        var c = str.charAt(i);
        if (c == textSeparator) {
            var p2;
            while (true) {
                p2 = str.indexOf(textSeparator, i + 1);
                work += str.substring(i + 1, p2);
                i = p2;

                // If this is a double quote, keep going!
                if (((p2 + 1) < str.length) && (str.charAt(p2 + 1) == textSeparator)) {
                    work += textSeparator;
                    i++;

                    // otherwise, this is a single quote, we're done
                }
                else {
                    break;
                }
            }
        }
        else if (c == separator) {
            list[list.length] = work.toString();
            work = '';
        }
        else {
            work += c;
        }
    }

    list[list.length] = work.toString();

    return list;
}


function ShowGuidePage(manual) {

    var filename = "";
    var pageSplit = manual.split('_')[0];

    if (pageSplit == "questionnaire")
        filename = "guideQuestionnaire.aspx";
    else if (pageSplit == "mindstedt")
        filename = "guideMindstedt.aspx";
    else if (pageSplit == "dagplejehjem")
        filename = "guideDagplejehjem.aspx";
    else if (pageSplit == "benchmarker")
        filename = "guideBenchmarker.aspx";
    else
        return;

    // If dialog already exists, it'll not be reopened, but just ignored.
    var dialogData = {
        name: "GuideDialog",
        type: "close",
        title: "Om Børnemiljøtermometeret",
        content: "Henter data...",
        width: 550,
        height: "70%",
        maxWidth: 0,
        maxHeight: 0,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);

    //ShowDialog("GuideDialog", "close", "Om Børnemiljøtermometeret", "Henter data...", null, null, null, 670, 500, 0, 0, "true");

    $("#GuideDialog #DialogGuideDialogContent").load(GetRootPath() + "/dialogs/" + filename, null, function() { $("#" + manual).css("display", "inline"); });

    var buttonsHtml = '<input type="button" class="button" value="Print denne vejledning" onclick="javascript:PrintManual(\'' + pageSplit + '\');" />&nbsp;&nbsp;&nbsp;';
    buttonsHtml += '<input type="button" class="button" id="Button2" value="Se anden vejledning" onclick="javascript:ShowChooseManualDialog();" />&nbsp;&nbsp;&nbsp;'
    buttonsHtml += '<input type="button" class="button" id="OkManualButton" value="Luk vindue" onclick="javascript:CloseDialog(\'GuideDialog\');" />';
    $("#ButtonsGuideDialog").css("text-align", "left");
    $("#ButtonsGuideDialog").html(buttonsHtml);
}

function ShowTermsAndConditions() {
    ShowDialog("TermsAndConditions", "close", "Vilkår", "Henter data...", null, null, null, 550, 400, 0, 0, "true");
    $("#TermsAndConditions #DialogTermsAndConditionsContent").load(GetRootPath() + "/dialogs/termsAndConditions.html");
}

function ShowBeregningsgrundlag() {
    ShowDialog("Beregningsgrundlag", "close", "Beregningsgrundlag", "Henter data...", null, null, null, 610, 420, 0, 0, "true");
    $("#Beregningsgrundlag #DialogBeregningsgrundlagContent").load(GetRootPath() + "/dialogs/beregningsgrundlag.html");
}

function ShowSupport() {
    var supportPage = GetSyncPage(GetRootPath() + "/dialogs/support.aspx");

    var dialogData = {
        name: "SupportDialog",
        type: "close",
        title: "Support",
        content: supportPage,
        width: 550,
        height: "70%",
        maxWidth: 0,
        maxHeight: 500,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);
    //ShowDialog("SupportDialog", "close", "Support", supportPage, null, null, null, 550, "auto", 0, 0, "true");

    var buttonsHtml = '<input type="button" class="button" value=" Send " onclick="javascript:SendSupport();" />&nbsp;&nbsp;';
    buttonsHtml += '<input type="button" class="button" value="Annuller" onclick="javascript:CloseDialog(\'SupportDialog\');" />';
    $("#ButtonsSupportDialog").css("text-align", "right");
    $("#ButtonsSupportDialog").html(buttonsHtml);
}

function ShowFeedback() {
    var feedbackPage = '';
    var feedbackPage = GetSyncPage(GetRootPath() + "/dialogs/feedback.aspx");

    var dialogData = {
        name: "FeedbackDialog",
        type: "close",
        title: "Feedback",
        content: feedbackPage,
        width: 550,
        height: "70%",
        maxWidth: 0,
        maxHeight: 500,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);
    //ShowDialog("FeedbackDialog", "close", "Feedback", feedbackPage, null, null, null, 550, "auto", 0, 0, "true");

    var buttonsHtml = '<input type="button" class="button" value=" Send " onclick="javascript:SendFeedback();" />&nbsp;&nbsp;';
    buttonsHtml += '<input type="button" class="button" value="Annuller" onclick="javascript:CloseDialog(\'FeedbackDialog\');" />';
    $("#ButtonsFeedbackDialog").css("text-align", "right");
    $("#ButtonsFeedbackDialog").html(buttonsHtml);
}


// Bruges, naar der skal aabnes resultatvisning i popup-vinduer.
function OpenResultDialog() {
    // Get all relevant data - this is all institutions, categories, surveys, when surveys closed, questionnaires, etc.
    var result = GetJSON(GetRootPath() + "/ResultWebServices.asmx/GetResultDialogData", null, false);
    var page = GetSyncPage(GetRootPath() + "/dialogs/resultDialog.aspx");

    var btnArray = new Array();
    var btn;

    //ShowDialog("ResultDialog", "close", "Resultatvisning", page, null, null, null, "90%", "70%", 0, 0, null, null, true, null, true);

    var dialogData = {
        name: "ResultDialog",
        type: "close",
        title: "Resultatvisning",
        content: page,
        width: "90%",
        height: "70%",
        maxWidth: 0,
        maxHeight: 0,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);

    resultDialogData = JSON.parse(result);

    fillQuestionnaireDropDown();
    doResizeResultDialogDivs();
}

function randomString(string_length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }

    return randomString;
}

function ShowDialogImproved(dialogData) {
    // DialogData can/must contain:
    var defaultValues = {
        name: randomString(10),
        type: "close", // close, working, yesno, ok
        title: "Dialog",
        content: "Termometeret",
        callbackYes: null,
        callbackNo: null,
        callbackOKClose: null,
        width: 500,
        height: 300,
        maxWidth: 0,
        maxHeight: 0,
        rightJustifyButtons: true,
        colortheme: null,
        closeWithEscape: false,
        btnArray: null,
        centerVertically: true,
        appendToForm: null,
        putOnTopDocument: false // true/false
    }

    if (dialogData.name === undefined)
        dialogData.name = defaultValues.name;
    if (dialogData.type === undefined)
        dialogData.type = defaultValues.type;
    if (dialogData.title === undefined)
        dialogData.title = defaultValues.title;
    if (dialogData.content === undefined)
        dialogData.content = defaultValues.content;
    if (dialogData.callbackYes === undefined)
        dialogData.callbackYes = defaultValues.callbackYes;
    if (dialogData.callbackNo === undefined)
        dialogData.callbackNo = defaultValues.callbackNo;
    if (dialogData.callbackOKClose === undefined)
        dialogData.callbackOKClose = defaultValues.callbackOKClose;
    if (dialogData.width === undefined)
        dialogData.width = defaultValues.width;
    if (dialogData.height === undefined)
        dialogData.height = defaultValues.height;
    if (dialogData.maxWidth === undefined)
        dialogData.maxWidth = defaultValues.maxWidth;
    if (dialogData.maxHeight === undefined)
        dialogData.maxHeight = defaultValues.maxHeight;
    if (dialogData.rightJustifyButtons === undefined)
        dialogData.rightJustifyButtons = defaultValues.rightJustifyButtons;
    if (dialogData.colortheme === undefined)
        dialogData.colortheme = defaultValues.colortheme;
    if (dialogData.closeWithEscape === undefined)
        dialogData.closeWithEscape = defaultValues.closeWithEscape;
    if (dialogData.btnArray === undefined)
        dialogData.btnArray = defaultValues.btnArray;
    if (dialogData.centerVertically === undefined)
        dialogData.centerVertically = defaultValues.centerVertically;
    if (dialogData.appendToForm === undefined)
        dialogData.appendToForm = defaultValues.appendToForm;
    if (dialogData.putOnTopDocument === undefined)
        dialogData.putOnTopDocument = defaultValues.putOnTopDocument;

    var theDocument;
    if (dialogData.putOnTopDocument != undefined && dialogData.putOnTopDocument != null && dialogData.putOnTopDocument == true)
        theDocument = top.document;
    else
        theDocument = document;

    for (i = 0; i < dialogsArray.length; i++)
        if (dialogsArray[i] == dialogData.name)
        return;

    var btnYesLabel = "  Ja  ";
    var btnNoLabel = "  Nej  ";
    var btnOKCloseLabel = "  OK  ";
    var btnJustify = "center";

    DialogZIndex += 50;

    dialogsArray[dialogsArray.length] = dialogData.name;

    if (dialogData.type == "close")
        btnOKCloseLabel = "  Luk  ";

    if (dialogData.rightJustifyButtons == true)
        btnJustify = "right";

    var dialogBorderCSS = 'jqmDialogWindowDefaultColors';
    var dialogTitleCSS = 'jqmDialogTitleDefaultColors';
    var btnCSS = 'button';
    var workingCSS = 'jqmDialogWorking';

    var DialogHTML = '';

    if (dialogData.type == "working") {
        DialogHTML += '<div id="' + dialogData.name + '" class="jqmDialog">';
        DialogHTML += '  <div class="' + dialogBorderCSS + ' jqmDialogWindow">';
        DialogHTML += '    <div id="Dialog' + dialogData.name + 'Window">';
        DialogHTML += '      <center>';
        DialogHTML += '        <br>';
        DialogHTML += '        <DIV id="Dialog' + dialogData.name + 'Content" style="height:auto;padding:7px;overflow:auto;">';
        DialogHTML += '          &nbsp;';
        DialogHTML += '        </DIV>';
        DialogHTML += '        <br>';
        DialogHTML += '        <div class="' + workingCSS + '"></div>';
        DialogHTML += '        <br>';
        DialogHTML += '      </center>';
        DialogHTML += '    </div>';
        DialogHTML += '  </div>';
        DialogHTML += '</div>';
    }
    else {
        DialogHTML += '<div id="' + dialogData.name + '" class="jqmDialog" style="width:100%; height:100%;">';
        DialogHTML += '  <div id="inner' + dialogData.name + '" class="' + dialogBorderCSS + ' jqmDialogWindow">';
        DialogHTML += '    <div id="Dialog' + dialogData.name + 'Window" style="height:100%;width:100%;">';
        DialogHTML += '      <DIV class="ui-layout-north" style="background-color:#FFFFFF;">  ';
        DialogHTML += '        <div id="DialogTitle" class="' + dialogTitleCSS + ' jqmDialogTitle">';
        DialogHTML += '          Overskrift';
        DialogHTML += '        </div>';
        DialogHTML += '      </DIV>';
        DialogHTML += '      <DIV class="ui-layout-center" id="Dialog' + dialogData.name + 'Content" style="height:auto;padding:7px;overflow:auto;">';
        DialogHTML += '      &nbsp;';
        DialogHTML += '      </DIV>';
        DialogHTML += '      <DIV id="Buttons' + dialogData.name + '" class="ui-layout-south" style="padding:5px;text-align:' + btnJustify + ';">';
        if (dialogData.btnArray != null) {
            for (i = 0; i < dialogData.btnArray.length; i++) {
                DialogHTML += '        <input type="button" class="' + btnCSS + '" value="' + dialogData.btnArray[i].label + '" onclick="' + dialogData.btnArray[i].click + '" />';

                if (dialogData.btnArray.length - 1 != i)
                    DialogHTML += "&nbsp;&nbsp;&nbsp;";
            }
        }
        else {
            DialogHTML += '        <input type="button" id="YesButton" class="' + btnCSS + '" value="' + btnYesLabel + '" />';
            DialogHTML += '        <input type="button" id="NoButton" class="' + btnCSS + '" value="' + btnNoLabel + '" />';
            DialogHTML += '        <input type="button" id="OKCloseButton" class="' + btnCSS + '" value="' + btnOKCloseLabel + '" />';
        }
        DialogHTML += '      </DIV>';
        DialogHTML += '    </div>';
        DialogHTML += '  </div>';
        DialogHTML += '</div>';
    }

    if (dialogData.appendToForm != null && dialogData.appendToForm != undefined)
        $("body", theDocument).find("#" + dialogData.appendToForm).append(DialogHTML);
    else
        $("body", theDocument).append(DialogHTML);

    $('#' + dialogData.name, theDocument).css("z-index", DialogZIndex);

    $('#' + dialogData.name, theDocument).jqm({ overlay: 25, modal: true, trigger: false });

    var preferedZIndex = DialogZIndex + 2;
    if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6")
        preferedZIndex = 50000; // Muligvis noedvendig for at popup i IE6 virker!

    $('#' + dialogData.name, theDocument)
    .jqmShow()
    .find('#Dialog' + dialogData.name + 'Content')
        .html(dialogData.content)
    .end();

    if (dialogData.type != "working")
        $('#' + dialogData.name, theDocument).find('#DialogTitle').html(dialogData.title).end();

    if (dialogData.width != "auto") {
        $('#inner' + dialogData.name, theDocument).width(dialogData.width);
        if (parseInt($('#inner' + dialogData.name, theDocument).width()) > dialogData.maxWidth && dialogData.maxWidth != 0) {
            $('#inner' + dialogData.name, theDocument).width(dialogData.maxWidth + "px");
        }
    }
    if (dialogData.height != "auto") {
        $('#inner' + dialogData.name, theDocument).height(dialogData.height);
        if (parseInt($('#inner' + dialogData.name, theDocument).height()) > dialogData.maxHeight && dialogData.maxHeight != 0) {
            $('#inner' + dialogData.name, theDocument).height(dialogData.maxHeight + "px");
        }
    }

    //var currentHeight = $('#' + dialogData.name + ' .jqmDialogWindow').height();
    //var currentWidth = $('#' + dialogData.name + ' .jqmDialogWindow').width();

    var currentHeight = $('#inner' + dialogData.name, theDocument).height();
    var currentWidth = $('#inner' + dialogData.name, theDocument).width();

    if (dialogData.width == "auto") {
        $('#inner' + dialogData.name, theDocument).css("width", currentWidth);
        $('#inner' + dialogData.name, theDocument).css("max-width", currentWidth);
    }
    if (dialogData.height == "auto") {
        $('#inner' + dialogData.name, theDocument).css("height", currentHeight);
        $('#inner' + dialogData.name, theDocument).css("max-height", currentHeight);
    }

    if (dialogData.type != "working") {
        $('#' + dialogData.name + " #Dialog" + dialogData.name + "Window").layout({ spacing_open: 0 });
    }

    var browserWindowWidth = $(window, theDocument).width();
    var browserWindowHeight = $(window, theDocument).height();
    var dialogWidth = $('#' + dialogData.name, theDocument).width();
    var dialogHeight = $('#' + dialogData.name, theDocument).height();

    $('#' + dialogData.name, theDocument).css("left", (browserWindowWidth / 2) - (dialogWidth / 2));

    // Centrer vindue!!!
    if (dialogData.centerVertically) {
        var topPosition = (browserWindowHeight / 2.0 - currentHeight / 2.0) + 'px';
        $('#' + dialogData.name, theDocument).addClass("modalCenterVertically");
        $('#' + dialogData.name, theDocument).css("top", topPosition);
    }

    $('#' + dialogData.name + ' .ui-layout-center', theDocument).css("z-index", preferedZIndex);
    $('#' + dialogData.name + ' .ui-layout-north', theDocument).css("z-index", preferedZIndex);
    $('#' + dialogData.name + ' .ui-layout-south', theDocument).css("z-index", preferedZIndex);

    if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6") {
        $('#' + dialogData.name, theDocument).css("z-index", 50000);
        $('#' + dialogData.name, theDocument).css("position", "absolute");
        $('#' + dialogData.name, theDocument).css("top", "100px");
        $('#' + dialogData.name, theDocument).css("left", "10px");
        $.scrollTo($('body', theDocument), 0);
    }

    if (dialogData.type == "yesno") {
        $('#' + dialogData.name, theDocument)
            .find('#YesButton')
                .show()
            .end()
            .find('#NoButton')
                .show()
            .end()
            .find('#OKCloseButton')
                .hide()
            .end();
    }
    else if (dialogData.type == "ok" || dialogData.type == "close") {
        $('#' + dialogData.name, theDocument)
            .find('#YesButton')
                .hide()
            .end()
            .find('#NoButton')
                .hide()
            .end()
            .find('#OKCloseButton')
                .show()
            .end();
    }

    if (dialogData.type != "working" && dialogData.type != null) {
        $('#' + dialogData.name, theDocument).find(':button:visible')
          .click(function() {

              if (this.value == btnYesLabel || this.value == btnNoLabel || this.value == btnOKCloseLabel)
                  CloseDialog(dialogData.name, dialogData.putOnTopDocument);

              if (this.value == btnYesLabel && typeof dialogData.callbackYes == 'function')
                  dialogData.callbackYes();
              else if (this.value == btnYesLabel && typeof dialogData.callbackYes == 'string')
                  eval(dialogData.callbackYes);
              else if (this.value == btnNoLabel && typeof dialogData.callbackNo == 'function')
                  dialogData.callbackNo();
              else if (this.value == btnNoLabel && typeof dialogData.callbackNo == 'string')
                  eval(dialogData.callbackNo);
              else if (this.value == btnOKCloseLabel && typeof dialogData.callbackOKClose == 'function')
                  dialogData.callbackOKClose();
              else if (this.value == btnOKCloseLabel && typeof dialogData.callbackOKClose == 'string')
                  eval(dialogData.callbackOKClose);
          });
    }

    if (dialogData.type == "yesno" || dialogData.type == "close" || dialogData.closeWithEscape) {
        escapeKeyDialogs[escapeKeyDialogs.length] = dialogData.name;
    }
}
