﻿/// <reference path="jQuery-vsdoc.js" />

var SystemSiteEnum = { "BMT": 1, "T3": 2 };
var currentSystemSite;
var currentStackTrace = '';

var ResultEnum = { Success: 1,
    Exists: 2,
    Error: 3,
    ValidationFailed: 4,
    LoginFailed: 5,
    ValidationFailed: 4,
    LoginFailed: 5,
    WrongPassword: 6,
    NoMatch: 7,
    NotStrongPassword: 8,
    NotAnonymous: 9
};

// ****** ERROR HANDLING *****

$.ajaxSetup({
    error: function (x, e) {
        if (x.status == 0) {
            alert('Du er ikke online!!\n Tjek eventuelt din netværksforbindelse.');
        } else if (x.status == 404) {
            alert("Kan ikke finde URL'en (404).");
        } else if (x.status == 500) {
            alert('Internal Server Error (505).');
        } else if (e == 'parsererror') {
            alert('Fejl.\nParsing JSON Request failed.');
        } else if (e == 'timeout') {
            alert('Der opstod en time out, da der skulle sendes eller modtages data fra serveren.');
        } else {
            alert('Ukendt fejl.\n' + x.responseText);
        }
    }
});


// Domain Public by Eric Wendelin http://eriwen.com/ (2008)
//                  Luke Smith http://lucassmith.name/ (2008)
//                  Loic Dachary <loic@dachary.org> (2008)
//                  Johan Euphrosine <proppy@aminche.com> (2008)
//                  Øyvind Sean Kinsey http://kinsey.no/blog (2010)
//
// Information and discussions
// http://jspoker.pokersource.info/skin/test-printstacktrace.html
// http://eriwen.com/javascript/js-stack-trace/
// http://eriwen.com/javascript/stacktrace-update/
// http://pastie.org/253058
// http://browsershots.org/http://jspoker.pokersource.info/skin/test-printstacktrace.html
//

//
// guessFunctionNameFromLines comes from firebug
//
// Software License Agreement (BSD License)
//
// Copyright (c) 2007, Parakey Inc.
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above
//   copyright notice, this list of conditions and the
//   following disclaimer.
//
// * Redistributions in binary form must reproduce the above
//   copyright notice, this list of conditions and the
//   following disclaimer in the documentation and/or other
//   materials provided with the distribution.
//
// * Neither the name of Parakey Inc. nor the names of its
//   contributors may be used to endorse or promote products
//   derived from this software without specific prior
//   written permission of Parakey Inc.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/**
*
* @cfg {Error} e The error to create a stacktrace from (optional)
* @cfg {Boolean} guess If we should try to resolve the names of anonymous functions
*/
//function printStackTrace(options) {
//    var ex = (options && options.e) ? options.e : null;
//    var guess = options ? !!options.guess : true;

//    var p = new printStackTrace.implementation();
//    var result = p.run(ex);
//    return (guess) ? p.guessFunctions(result) : result;
//}

//printStackTrace.implementation = function() { };

//printStackTrace.implementation.prototype = {
//    run: function(ex) {
//        // Use either the stored mode, or resolve it
//        var mode = this._mode || this.mode();
//        if (mode === 'other') {
//            return this.other(arguments.callee);
//        } else {
//            ex = ex ||
//                (function() {
//                    try {
//                        (0)();
//                    } catch (e) {
//                        return e;
//                    }
//                })();
//            return this[mode](ex);
//        }
//    },

//    mode: function() {
//        try {
//            (0)();
//        } catch (e) {
//            if (e.arguments) {
//                return (this._mode = 'chrome');
//            } else if (e.stack) {
//                return (this._mode = 'firefox');
//            } else if (window.opera && !('stacktrace' in e)) { //Opera 9-
//                return (this._mode = 'opera');
//            }
//        }
//        return (this._mode = 'other');
//    },

//    chrome: function(e) {
//        return e.stack.replace(/^.*?\n/, '').
//                replace(/^.*?\n/, '').
//                replace(/^.*?\n/, '').
//                replace(/^[^\(]+?[\n$]/gm, '').
//                replace(/^\s+at\s+/gm, '').
//                replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@').
//                split('\n');
//    },

//    firefox: function(e) {
//        return e.stack.replace(/^.*?\n/, '').
//                replace(/(?:\n@:0)?\s+$/m, '').
//                replace(/^\(/gm, '{anonymous}(').
//                split('\n');
//    },

//    // Opera 7.x and 8.x only!
//    opera: function(e) {
//        var lines = e.message.split('\n'), ANON = '{anonymous}',
//            lineRE = /Line\s+(\d+).*?script\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i, i, j, len;

//        for (i = 4, j = 0, len = lines.length; i < len; i += 2) {
//            if (lineRE.test(lines[i])) {
//                lines[j++] = (RegExp.$3 ? RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 : ANON + '()@' + RegExp.$2 + ':' + RegExp.$1) +
//                ' -- ' +
//                lines[i + 1].replace(/^\s+/, '');
//            }
//        }

//        lines.splice(j, lines.length - j);
//        return lines;
//    },

//    // Safari, Opera 9+, IE, and others
//    other: function(curr) {
//        var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], j = 0, fn, args;

//        var maxStackSize = 10;
//        while (curr && stack.length < maxStackSize) {
//            fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
//            args = Array.prototype.slice.call(curr['arguments']);
//            stack[j++] = fn + '(' + printStackTrace.implementation.prototype.stringifyArguments(args) + ')';

//            //Opera bug: if curr.caller does not exist, Opera returns curr (WTF)
//            if (curr === curr.caller && window.opera) {
//                //TODO: check for same arguments if possible
//                break;
//            }
//            curr = curr.caller;
//        }
//        return stack;
//    },

//    /**
//    * @return given arguments array as a String, subsituting type names for non-string types.
//    */
//    stringifyArguments: function(args) {
//        for (var i = 0; i < args.length; ++i) {
//            var argument = args[i];
//            if (typeof argument == 'object') {
//                args[i] = '#object';
//            } else if (typeof argument == 'function') {
//                args[i] = '#function';
//            } else if (typeof argument == 'string') {
//                args[i] = '"' + argument + '"';
//            }
//        }
//        return args.join(',');
//    },

//    sourceCache: {},

//    /**
//    * @return the text from a given URL.
//    */
//    ajax: function(url) {
//        var req = this.createXMLHTTPObject();
//        if (!req) {
//            return;
//        }
//        req.open('GET', url, false);
//        req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
//        req.send('');
//        return req.responseText;
//    },

//    createXMLHTTPObject: function() {
//        // Try XHR methods in order and store XHR factory
//        var xmlhttp, XMLHttpFactories = [
//            function() {
//                return new XMLHttpRequest();
//            }, function() {
//                return new ActiveXObject('Msxml2.XMLHTTP');
//            }, function() {
//                return new ActiveXObject('Msxml3.XMLHTTP');
//            }, function() {
//                return new ActiveXObject('Microsoft.XMLHTTP');
//            }
//        ];
//        for (var i = 0; i < XMLHttpFactories.length; i++) {
//            try {
//                xmlhttp = XMLHttpFactories[i]();
//                // Use memoization to cache the factory
//                this.createXMLHTTPObject = XMLHttpFactories[i];
//                return xmlhttp;
//            } catch (e) { }
//        }
//    },

//    getSource: function(url) {
//        if (!(url in this.sourceCache)) {
//            this.sourceCache[url] = this.ajax(url).split('\n');
//        }
//        return this.sourceCache[url];
//    },

//    guessFunctions: function(stack) {
//        for (var i = 0; i < stack.length; ++i) {
//            var reStack = /{anonymous}\(.*\)@(\w+:\/\/([-\w\.]+)+(:\d+)?[^:]+):(\d+):?(\d+)?/;
//            var frame = stack[i], m = reStack.exec(frame);
//            if (m) {
//                var file = m[1], lineno = m[4]; //m[7] is character position in Chrome
//                if (file && lineno) {
//                    var functionName = this.guessFunctionName(file, lineno);
//                    stack[i] = frame.replace('{anonymous}', functionName);
//                }
//            }
//        }
//        return stack;
//    },

//    guessFunctionName: function(url, lineNo) {
//        try {
//            return this.guessFunctionNameFromLines(lineNo, this.getSource(url));
//        } catch (e) {
//            return 'getSource failed with url: ' + url + ', exception: ' + e.toString();
//        }
//    },

//    guessFunctionNameFromLines: function(lineNo, source) {
//        var reFunctionArgNames = /function ([^(]*)\(([^)]*)\)/;
//        var reGuessFunction = /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*(function|eval|new Function)/;
//        // Walk backwards from the first line in the function until we find the line which
//        // matches the pattern above, which is the function definition
//        var line = "", maxLines = 10;
//        for (var i = 0; i < maxLines; ++i) {
//            line = source[lineNo - i] + line;
//            if (line !== undefined) {
//                var m = reGuessFunction.exec(line);
//                if (m && m[1]) {
//                    return m[1];
//                } else {
//                    m = reFunctionArgNames.exec(line);
//                    if (m && m[1]) {
//                        return m[1];
//                    }
//                }
//            }
//        }
//        return '(?)';
//    }
//};

window.defaultOnError = window.onerror; // save current error handler
window.onerror = handleError;

var lastErrorTickCount = 0;
var lastErr = '';
var MIN_TIME_BETWEEN_ERRORS = 1000;

// set new error handler
function handleError(err, url, line) {
    var tmpStackTrace = currentStackTrace;

    var date = new Date();
    var ticks = date.getTime();

    // Same errors occurs several times in short interval? Then turn off
    // custom error handling
    if (ticks - lastErrorTickCount < MIN_TIME_BETWEEN_ERRORS && err == lastErr) {
        window.onerror = window.defaultOnError;
        return false;
    }
    lastErrorTickCount = ticks;
    lastErr = err;
    var browserInfo = getBrowserInfo();
    var osInfo = getOSInfo();
    var resolution = getScreenResolution();
    var userInfo = getUserInfo();
    //    var trace = JSON.stringify(printStackTrace());

    var errorData = {
        errorData: { err: err,
            url: url,
            line: line,
            browser: browserInfo,
            osInfo: osInfo,
            resolution: resolution,
            userInfo: userInfo,
            trace: "ej implementeret",
            currentStackTrace: JSON.stringify(tmpStackTrace)
        }
    };

    var data = JSON.stringify(errorData);

    GetJSON(GetRootPath() + "/webservices/CommonWebServices.asmx/LogJavascriptError", data, false);

    return false; // on the client, the browser now controls the rest of error handling...
}

// Set an error handler for a function
//Function.prototype.updateStackTracer =
//  function(f, v) {
//      // Throw error if no user function is provided
//      var that = this;
//      var g =
//      function() {
//          var a = [];

//          currentStackTrace = printStackTrace();

//          for (var i = 0; i < arguments.length; i++)
//              a.push(arguments[i]);
//          return that.apply(null, a);
//      };
//      // Save ref. to original function
//      g.old = this;
//      return g;
//  };


function getAllFunctions() {

    var functions = new Array();
    for (var i in window) {
        if (typeof parent[i] === 'function') {
            functions.push(parent[i].getName());
        }
    }

    return functions;
}

function allowedToAddStackTracer(functionName) {
    if (functionName.indexOf('setErrorHandlingOnAllFunctions') != -1 ||
    functionName.indexOf('getAllFunctions') != -1 ||
    functionName.indexOf('updateStackTracer') != -1 ||
    functionName.indexOf('handleError') != -1 ||
    functionName.indexOf('allowedToAddStackTracer') != -1 ||
    functionName.indexOf('alert') != -1 ||
    functionName.indexOf('postMessage') != -1 ||
    functionName.indexOf('showModalDialog') != -1 ||
    functionName.indexOf('printStackTrace') != -1 ||
    functionName.indexOf('mouseover') != -1 ||
    functionName.indexOf('mousemove') != -1 ||
    functionName.indexOf('tt_') != -1 ||
    functionName.indexOf('anonymous') != -1)
        return false;

    return true;
}

function setErrorHandlingOnAllFunctions() {
    var allFunctionNames = getAllFunctions();

    for (i = 0; i < allFunctionNames.length; i++) {
        if (allowedToAddStackTracer(allFunctionNames[i])) {
            eval(allFunctionNames[i] + " = " + allFunctionNames[i] + ".updateStackTracer()");
        }
    }
}

// Return the name of a function
Function.prototype.getName =
  function () {
      var m = this.toString().match(/^function\s(\w+)/);
      return m ? m[1] : "anonymous";
  };

//$(document).ready(function() {
//    setErrorHandlingOnAllFunctions();
//});

// ***************************

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 disableEnterKey(e, clickElementName) {
    var keycode;
    if (window.event)
        keycode = window.event.keyCode;
    else if (e)
        keycode = e.which;

    if (keycode == 13) {
        if (typeof (clickElementName) != "undefined" && clickElementName != null)
            $("#[id$='" + clickElementName + "']").trigger('click');

        return false;
    }

    return true;
}

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 LogOut() {
    GetJSON(GetRootPath() + "/webservices/CommonWebServices.asmx/LogoutAll", null, false);
    GoToRootPage();
}

function LogOutBenchmarker() {
    GetJSON(GetRootPath() + "/webservices/CommonWebServices.asmx/LogoutBenchmarker", null, false);
    GoToRootPage();
}

function LogOutInstitution() {
    GetJSON(GetRootPath() + "/webservices/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);

    parent.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, onTopDocument) {

    var theDocument;
    if (onTopDocument != undefined && onTopDocument != null)
        theDocument = top.document;
    else
        theDocument = document;

    $('#' + name, theDocument).jqmHide();
    $('#' + name, theDocument).remove();
    escapeKeyDialogs.remove(name);
    dialogsArray.remove(name);

    if (dialogsArray.length == 0)
        DialogZIndex = 3000;
}

// Returns true if a jquery-element is checkable (radiobutton or checkbox)
function IsCheckable(jQueryElement) {
    var type = jQueryElement.attr('type');
    return /radio|checkbox/i.test(type);
}

// Returns true if a jquery-element is a dropdown (select-one)
function IsDropDown(jQueryElement) {
    var type = jQueryElement.attr('type');
    return /select/i.test(type);
}

function IsTextBox(jQueryElement) {
    return IsInput(jQueryElement) && jQueryElement.attr('type').toLowerCase() == "text";
}

function IsCheckBox(jQueryElement) {
    return IsInput(jQueryElement) && jQueryElement.attr('type').toLowerCase() == "checkbox";
}

function IsTextArea(jQueryElement) {
    var type = jQueryElement.get(0).tagName;
    return /textarea/i.test(type);
}

function IsInput(jQueryElement) {
    var type = jQueryElement.get(0).tagName;
    return /input/i.test(type);
}

// Returns true if jquery-element is a SPAN
function IsSpan(jQueryElement) {
    var type = jQueryElement.get(0).tagName;
    return /span/i.test(type);
}

// 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, dontPrefixWithButtons) {
    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].id != null)
                buttonHTML += 'id="' + btnArray[i].id + '"';

            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>";

        if (dontPrefixWithButtons)
            $("#" + divName).html(buttonHTML);
        else
            $("#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 OpenAverageDialog(type) {
    // Get the average page
    var page = GetSyncPageNoCache(GetRootPath() + "/dialogs/AverageDialog.aspx?type=" + type);
    var btnArray = new Array();
    var btn;
    var title = (type == "municipality" ? "Kommunalt gennemsnit" : "Landsgennemsnit");

    ShowDialog("AverageDialog", "close", title, page, null, null, null, 650, "70%", 0, 0, true, null, true, null, true);
}

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:
    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="margin:0px;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%;">';
        if (typeof dialogData.height != 'number' && dialogData.height.indexOf("%") != -1) // we use height in pct, so we'll need to set the total height to 100%
            DialogHTML += '<div id="' + dialogData.name + '" class="jqmDialog" style="height:100%;">';
        else
            DialogHTML += '<div id="' + dialogData.name + '" class="jqmDialog">';
        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' + dialogData.name + '" 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;margin:0px;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' + dialogData.name).html(dialogData.title);

    //    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 = $('#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);
    //    }

    //    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;
    }

    UpdateSizeDialog(dialogData);
}

// TODO: Kontroller blandt andet om alle popups virker, hvis appendToForm altid er sat til aspnetForm!
function ShowDialog(name, type, title, content, callbackYes, callbackNo, callbackOKClose, width, height, maxWidth, maxHeight, rightjustifyButtons, colortheme, closeWithEscape, btnArray, centerVertically, appendToForm) {

    var dialogData = new Object();

    dialogData = {
        name: name,
        type: type,
        title: title,
        content: content,
        callbackYes: callbackYes,
        callbackNo: callbackNo,
        callbackOKClose: callbackOKClose,
        width: width,
        height: height,
        maxWidth: maxWidth,
        maxHeight: maxHeight,
        rightJustifyButtons: rightjustifyButtons,
        colortheme: colortheme,
        closeWithEscape: closeWithEscape,
        btnArray: btnArray,
        centerVertically: centerVertically,
        appendToForm: appendToForm,
        putOnTopDocument: false
    };

    ShowDialogImproved(dialogData);
}

$(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 SetFloatingMessage(message) {

    // Stop animation (if any) and hide panel
    $("#[id$='PanelFloatingMessageParent']").stop(true, true);

    // Then set colors and show
    $("#[id$='PanelFloatingMessageParent']").css("background-color", "#ccffcc");
    $("#[id$='PanelFloatingMessage']").css("color", "#00ff00");

    if (message.startsWith("SUCCESS-"))
        message = message.substr(8);
    else if (message.startsWith("INFO-")) {
        message = message.substr(5);
        $("#[id$='PanelFloatingMessageParent']").css("background-color", "#ccccff");
        $("#[id$='PanelFloatingMessage']").css("color", "#0000ff");
    }
    else if (message.startsWith("ERROR-")) {
        message = message.substr(6);
        $("#[id$='PanelFloatingMessageParent']").css("background-color", "#ffcccc");
        $("#[id$='PanelFloatingMessage']").css("color", "#ff0000");
    }

    $("#[id$='PanelFloatingMessage']").html(message);
    $("#[id$='PanelFloatingMessageParent']").css("display", "inline");
    $("#[id$='PanelFloatingMessageParent']").animate({ foo: 1 }, 3000).fadeOut(2000);
}

function GetSyncPageNoCache(page) {
    var result = '';

    $.ajax({
        url: page,
        cache: false,
        async: false,
        success: function (html) {
            result = html;
        },
        error: function (request, errorType, errorThrown) {
            alert("fejl: " + errorType + " :: " + errorThrown);
        }
    });

    return result;
}

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);
        }
    });
}

// Gets data sync. 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 GetSyncJSOBJ(service, object) {
    var jsonData;

    if (object == null)
        jsonData = "{}";
    else
        jsonData = JSON.stringify(object);

    return GetJSON(service, jsonData, false);
}

//
function webServiceSync(serviceroot, service, callback, jsonData) {

    var servicepath = GetRootPath() + "/webservices/" + serviceroot + ".asmx/" + service;

    var result = GetJSON(servicepath, jsonData, false);

    if (callback != null)
        callback(result);
}

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;
}

var execute = false;
function SetConfirmationButton(buttonId, title, message) {
    var resultFromConfirmBox = false;
    $("#" + buttonId)
        .unbind('click')
        .click(function (e) {
            //We keep the original click event so
            //it can be executed as a callback
            var target = $(e.target);

            //Check if the control is a button or a link
            if (target.attr("href")) {
                callback = function () { execute = true; window.location.href = target.attr("href"); };
            }
            else {
                callback = function () { execute = true; resultFromConfirmBox = true; target.click(); };
            }

            //Register popup and yes callback
            if (!resultFromConfirmBox)
                DoConfirm("yesno", title, message, "QUESTION", callback, null, null);

            //If execute is true, it means that it was set by the yes callback
            //and so we should return true in order to not interfer with the form submission
            var result = execute;
            execute = false;
            return result;
        });
}



function DoConfirm(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;

    var html = GetIconTableHtml(icon, msg);

    var dialogData = {
        name: "ConfirmBox",
        type: "yesno",
        title: title,
        content: html,
        width: 300,
        height: "auto",
        maxWidth: 0,
        maxHeight: 0,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true,
        callbackYes: callbackYes,
        callbackNo: callbackNo,
        callbackOKClose: callbackOK
    }

    ShowDialogImproved(dialogData);
}

$().ready(function () {
    //Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

    if (window["HandleMessages"] != null)
        HandleMessages();

    if (window["UpdateRow"] != null)
        UpdateRow();

    if (typeof ("placeFooterText") == "function")
        placeFooterText();

    currentSystemSite = GetSyncJSOBJ(GetRootPath() + "/webservices/DCUMWebServices.asmx/GetSystemSite", null);

    // 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() {
    parent.pleaseWaitCounter++;

    if (parent.document.getElementById('PleaseWaitDiv') != null)
        parent.document.getElementById('ImagePleaseWait').style.display = "inline";
}

function hidePleaseWait() {
    if (parent.pleaseWaitCounter > 0) {
        parent.pleaseWaitCounter--;
        if (parent.pleaseWaitCounter == 0 && parent.document.getElementById('PleaseWaitDiv') != null)
            parent.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'); });
}

// Add clickable rows to a table and set callbacks for checked and unchecked...
// The trClass-parameter can be NULL/undefined. It filters on the clicked row name also
// The sentCheckBoxID can be NULL/undefined. If true, it'll send the checkbox ID til the callback functions.
function addClickMarkCheckbox(tablename, prefix, callbackChecked, callbackUnchecked, trClass, sentCheckBoxID, tdClass) {
    var clickSelection;

    if (tdClass != undefined && tdClass != null)
        clickSelection = '#' + tablename + ' .' + tdClass;
    else if (trClass != undefined && trClass != null)
        clickSelection = '#' + tablename + ' .' + trClass;
    else
        clickSelection = '#' + tablename + ' tbody tr ';

    $(clickSelection).click(function (event) {

        var isChecked;
        var checkboxId;
        var $elementTR;

        if (this.tagName.toLowerCase() != "tr") {
            // If a TD or the checkbox is clicked we move to the TR
            $elementTR = $(this).closest("tr");
        }
        else
            $elementTR = $(this);

        // Get current status
        isChecked = $elementTR.find("#[id*='" + prefix + "']:checked:first").length == 1;

        // (If we clicked on a checkbox, it will immediatly be set.
        // If clicked on a TD we have to mark the checkbox ourselves)
        if (event.target.type !== 'checkbox') {
            $elementTR.find("#[id*='" + prefix + "']").attr('checked', !isChecked);
            isChecked = !isChecked; // update checked-value
        }

        checkboxId = $elementTR.find("#[id*='" + prefix + "']").attr('id');

        // Update layout of tr
        if (isChecked) {
            $elementTR.addClass('selected');
        }
        else {
            $elementTR.removeClass('selected');
        }

        // Do callbacks (if set)
        if (isChecked && typeof (callbackChecked) === "function") {
            if (sentCheckBoxID != undefined && sentCheckBoxID != null && sentCheckBoxID == true)
                callbackChecked(checkboxId);
            else
                callbackChecked();
        }
        else if (!isChecked && typeof (callbackUnchecked) === "function") {
            if (sentCheckBoxID != undefined && sentCheckBoxID != null && sentCheckBoxID == true)
                callbackUnchecked(checkboxId);
            else
                callbackUnchecked();
        }
    });
}

// Returns index
Array.prototype.contains = function (value) {
    for (arrI = 0; arrI < this.length; arrI++)
        if (this[arrI] == value)
            return arrI;

    return -1;
}

// Returns true/false
Array.prototype.containsTF = function (value) {
    for (arrI = 0; arrI < this.length; arrI++)
        if (this[arrI] == value)
            return true;

    return false;
}

Array.prototype.unique = function () {
    this.sort();
    for (var i = 1; i < this.length; ) {
        if (this[i - 1] == this[i]) { this.splice(i, 1); }
        else { i++; }
    }
    return this;
}

function htmlEncode(str) {
    str = str.replace(new RegExp("<", "g"), '&lt;');
    str = str.replace(new RegExp(">", "g"), '&gt;');
    return str;
}

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'>" + URLDecode(this.t) + "</p>");
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.css("z-index", "20000")
			.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() + '/dokumenter/vejledning_til_fritidshjem_boernehavens_4_til_6.pdf', '', '');
    else if (guideToPrint == 'benchmarker')
        window.open(GetRootPath() + '/dokumenter/vejledning_til_benchmarking.pdf', '', '');
    else if (guideToPrint == 'dagplejehjem')
        window.open(GetRootPath() + '/dokumenter/vejledning_til_dagplejen.pdf', '', '');
    else if (guideToPrint == 'mindstedt')
        window.open(GetRootPath() + '/dokumenter/vejledning_til_vuggestue_og_boernehave.pdf', '', '');

    else if (guideToPrint == 'grundsfo')
        window.open(GetRootPath() + '/dokumenter/vejledning_til_grundskole.pdf', '', '');
    else if (guideToPrint == 'ungvoksen')
        window.open(GetRootPath() + '/dokumenter/vejledning_til_ungvoksen.pdf', '', '');
    else if (guideToPrint == 'benchmarkerterm')
        window.open(GetRootPath() + '/dokumenter/vejledning_til_benchmarking_termometer.pdf', '', '');
}

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

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(GetRootPath() + "/webservices/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(GetRootPath() + "/webservices/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(onlyGrundskole) {

    var dialogData = {
        name: "GuideFrontpageDialog",
        type: "close",
        title: "Vejledninger",
        content: "Henter data...",
        width: 650,
        height: 220,
        maxWidth: 0,
        maxHeight: 500,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);

    var param = '';
    if (typeof (onlyGrundskole) != "undefined")
        param = "?grundskole=true";

    $("#GuideFrontpageDialog #DialogGuideFrontpageDialogContent").load(GetRootPath() + "/dialogs/guideFrontpage.aspx" + param);
}

function ShowAboutBMT() {

    var dialogData = {
        name: "AboutDialog",
        type: "close",
        title: "Om Børnemiljøtermometeret",
        content: "Henter data...",
        width: 550,
        height: "70%",
        maxWidth: 0,
        maxHeight: 500,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);
    //ShowDialog("AboutDialog", "close", "Om Børnemiljøtermometeret", "Henter data...", null, null, null, 550, 400, 0, 0, "true");
    $("#" + "AboutDialog #DialogAboutDialogContent").load(GetRootPath() + "/dialogs/aboutBMT.html");
}

function ShowAboutTermometeret() {

    var dialogData = {
        name: "AboutDialog",
        type: "close",
        title: "Om Termometeret",
        content: "Henter data...",
        width: 550,
        height: "70%",
        maxWidth: 0,
        maxHeight: 500,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);
    //ShowDialog("AboutDialog", "close", "Om Termometeret", "Henter data...", null, null, null, 550, 400, 0, 0, "true");
    $("#" + "AboutDialog #DialogAboutDialogContent").load(GetRootPath() + "/dialogs/aboutTermometeret.html");
}

function doResizeJQueryTabs() {

    if ($("#[id*='fragment-']").length > 0) {

        var height;
        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");
    }

    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).height();  // TOPDOCUMENT
    var browserWindowWidth = $(window).width();
    //alert(browserWindowHeight);
    $('.modalCenterVertically').each(function () {
        var name = $(this).attr("id");
        var currentHeight = $('#inner' + name).height(); // TOPDOCUMENT
        var topPosition = (browserWindowHeight / 2.0 - currentHeight / 2.0) + 'px';
        $(this).css("top", topPosition);
    });

    $('.modalCenterHorizontally').each(function () {
        var name = $(this).attr("id");
        var currentWidth = $('#inner' + name).width(); // TOPDOCUMENT
        var leftPosition = (browserWindowWidth / 2.0 - currentWidth / 2.0) + 'px';
        $(this).css("left", leftPosition);
    });
}

// $(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).resize(function () {
    doResizing();
});

function doResizing() {
    doResizeJQueryTabs();
    doResizeCenteredModals();

    if (typeof (doResizeResultDialogDivs) != "undefined")
        doResizeResultDialogDivs();

    if (resizeTimer)
        clearTimeout(resizeTimer);

    resizeTimer = setTimeout(doResizeJQueryTabs, 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.startsWith = function (str)
{ return (this.match("^" + str) == str) }

String.prototype.trim = function () { return this.replace(/^\s*/, "").replace(/\s*$/, ""); }

function SplitCSV(str) {
    // 360,'Her er,, en "forfærdelig" 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 ShowQuestionsInCategory(categoryIDs, termReplacementIDs) {

    showPleaseWait();

    var queryString;
    queryString = "catID=" + categoryIDs;

    if (termReplacementIDs != undefined && termReplacementIDs != null)
        queryString += "&termReplacementIDs=" + termReplacementIDs;

    var questionsPage = GetSyncPageNoCache(GetRootPath() + "/dialogs/QuestionsInCategory.aspx?" + queryString);

    var dialogData = {
        name: "QuestionsDialog",
        type: "close", // kan vaere: close, working, yesno, ok (eller null)
        title: "Spørgsmål",
        content: questionsPage, // noget html, som bliver vist i vinduet
        width: 550,
        height: "auto",
        maxWidth: 0,
        maxHeight: "70%",
        rightJustifyButtons: true, // om knapper skal placeres til hoejre
        closeWithEscape: true, // Man kan lukke vinduet ved tryk paa ESC
        centerVertically: true // Centreres midt i browservinduet
    }

    ShowDialogImproved(dialogData);

    hidePleaseWait();
}

function UpdateHeightDialog(dialogData, theDocument) {

    var currentHeight = $('#inner' + dialogData.name, theDocument).outerHeight();

    var browserWindowHeight = $(window, theDocument).height();
    var dialogHeight = $('#' + dialogData.name, theDocument).height();

    var maxHeight = 0;
    if (dialogData.maxHeight != 0) {
        maxHeight = dialogData.maxHeight;

        if (dialogData.maxHeight.toString().indexOf("%") != -1)
            maxHeight = parseInt(browserWindowHeight * parseFloat(dialogData.maxHeight) / 100.0);
    }

    var buttonHeight = 0;
    // We set the height to AUTO, so that it'll expand to fit the button div
    // Afterwards we set the height - and get the outerheight...
    $('#Buttons' + dialogData.name, theDocument).height("auto");
    buttonHeight = $('#Buttons' + dialogData.name, theDocument).height();
    $('#Buttons' + dialogData.name, theDocument).height(buttonHeight);
    buttonHeight = $('#Buttons' + dialogData.name, theDocument).outerHeight();

    var titleHeight = $('#DialogTitle' + dialogData.name, theDocument).outerHeight();

    var contentHeight = 0;
    var paddingHeight = 0;
    var height = 0;

    paddingHeight += parseInt($("#Dialog" + dialogData.name + "Content").css("padding-top"));
    paddingHeight += parseInt($("#Dialog" + dialogData.name + "Content").css("padding-bottom"));

    // HEIGHT
    if ($("#Dialog" + dialogData.name + "Content").children().length == 0)
        contentHeight += $("#Dialog" + dialogData.name + "Content").outerHeight();
    else {
        //contentHeight += $("#Dialog" + dialogData.name + "Content").children().outerHeight();
        $("#Dialog" + dialogData.name + "Content").children().each(function () {
            contentHeight += $(this).outerHeight();
        });
    }

    if (dialogData.height == "auto")
        height = contentHeight + buttonHeight + titleHeight + paddingHeight;
    else if (dialogData.height.toString().indexOf("%") != -1)
        height = browserWindowHeight * parseInt(dialogData.height) * 0.01;
    else
        height = dialogData.height + buttonHeight + titleHeight + paddingHeight;

    var innerContentHeight = 0;
    innerContentHeight = height - buttonHeight - titleHeight - paddingHeight;

    // Setting the height
    if (maxHeight != 0 && height > maxHeight) {
        $('#inner' + dialogData.name, theDocument).css("height", maxHeight);
        $("#Dialog" + dialogData.name + "Content").css("height", maxHeight - buttonHeight - titleHeight - paddingHeight);

        //$("#Dialog" + dialogData.name + "Content").css("max-height", dialogData.maxHeight);
        //$('#inner' + dialogData.name, theDocument).css("max-height", dialogData.maxHeight);
    }
    else {
        $('#inner' + dialogData.name, theDocument).css("height", height);
        $("#Dialog" + dialogData.name + "Content").css("height", innerContentHeight);
    }
    // Finished setting the height

    currentHeight = $('#inner' + dialogData.name, theDocument).outerHeight();

    if (dialogData.centerVertically) {
        var topPosition = (browserWindowHeight / 2.0 - currentHeight / 2.0) + 'px';
        $('#' + dialogData.name, theDocument).addClass("modalCenterVertically");
        $('#' + dialogData.name, theDocument).css("top", topPosition);
    }
}

function UpdateWidthDialog(dialogData, theDocument) {

    var currentWidth = $('#inner' + dialogData.name, theDocument).outerWidth();
    var browserWindowWidth = $(window, theDocument).width();
    var dialogWidth = $('#' + dialogData.name, theDocument).width();

    var maxWidth = 0;
    if (dialogData.maxWidth != 0) {
        maxWidth = dialogData.maxWidth;

        if (dialogData.maxWidth.toString().indexOf("%") != -1)
            maxWidth = parseInt(browserWindowWidth * parseFloat(dialogData.maxWidth) / 100.0);
    }

    var contentWidth = 0;
    var paddingWidth = 0;
    var width = 0;

    paddingWidth += parseInt($("#Dialog" + dialogData.name + "Content").css("padding-left"));
    paddingWidth += parseInt($("#Dialog" + dialogData.name + "Content").css("padding-right"));

    if ($("#Dialog" + dialogData.name + "Content").children().length == 0)
        contentWidth += $("#Dialog" + dialogData.name + "Content").outerWidth();
    else
        contentWidth += $("#Dialog" + dialogData.name + "Content").children().outerWidth();

    if (dialogData.width == "auto")
        width = contentWidth + paddingWidth;
    else if (dialogData.width.toString().indexOf("%") != -1)
        width = browserWindowWidth * parseInt(dialogData.width) * 0.01;
    else
        width = dialogData.width + paddingWidth;

    var innerContentWidth = 0;
    innerContentWidth = width - paddingWidth;

    // Setting the width
    if (dialogData.width == "auto") {
        $('#inner' + dialogData.name, theDocument).css("width", currentWidth);
        $('#inner' + dialogData.name, theDocument).css("max-width", currentWidth);
    }
    else if (maxWidth != 0 && width > maxWidth) {
        $('#inner' + dialogData.name, theDocument).css("width", maxWidth);
        $("#Dialog" + dialogData.name + "Content").css("width", maxWidth);
    }
    else {
        $('#inner' + dialogData.name, theDocument).css("width", width);
        $("#Dialog" + dialogData.name + "Content").css("width", innerContentWidth);
    }
    // Finished setting the width

    currentWidth = $('#inner' + dialogData.name, theDocument).outerWidth();

    // Center window horizontally
    if (!($.browser.msie && $.browser.version == 7.0) || currentSystemSite == SystemSiteEnum.BMT) {
        var leftPosition = (browserWindowWidth / 2.0 - currentWidth / 2.0) + 'px';
        $('#' + dialogData.name, theDocument).addClass("modalCenterHorizontally");
        $('#' + dialogData.name, theDocument).css("left", leftPosition);
    }
}

function UpdateSizeDialog(dialogData) {

    var theDocument;
    if (dialogData.putOnTopDocument != undefined && dialogData.putOnTopDocument != null && dialogData.putOnTopDocument == true)
        theDocument = top.document;
    else
        theDocument = document;

    // Set the width and height (according to dialogData)
    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");
        }
    }

    UpdateHeightDialog(dialogData, theDocument);
    UpdateWidthDialog(dialogData, theDocument);

    //    $('#Buttons' + dialogData.name, theDocument).css("background-color", "#aa77bb");
    //    $('#DialogTitle' + dialogData.name, theDocument).css("background-color", "green");
    //    $('#inner' + dialogData.name, theDocument).css("background-color", "cyan");
    //    $("#Dialog" + dialogData.name + "Content").css("background-color", "#aaaaaa");

    if (dialogData.type != "working")
        $('#' + dialogData.name + " #Dialog" + dialogData.name + "Window").layout({ spacing_open: 0 });
}

function ShowGuidePage(manual) {

    var filename = "";
    var pageSplit = manual.split('_')[0];
    var leftarrowsrc = "images/arrow_left_active.png";
    var rightarrowsrc = "images/arrow_right_active.png";

    //BMT
    if (pageSplit == "questionnaire") {
        filename = "guideQuestionnaire.aspx";
        leftarrowsrc = "images/arrow_left_active_bmt.png";
        rightarrowsrc = "images/arrow_right_active_bmt.png";
    }
    else if (pageSplit == "mindstedt") {
        filename = "guideMindstedt.aspx";
        leftarrowsrc = "images/arrow_left_active_bmt.png";
        rightarrowsrc = "images/arrow_right_active_bmt.png";
    }
    else if (pageSplit == "dagplejehjem") {
        filename = "guideDagplejehjem.aspx";
        leftarrowsrc = "images/arrow_left_active_bmt.png";
        rightarrowsrc = "images/arrow_right_active_bmt.png";
    }
    else if (pageSplit == "benchmarker") {
        filename = "guideBenchmarkerBMT.aspx";
        leftarrowsrc = "images/arrow_left_active_bmt.png";
        rightarrowsrc = "images/arrow_right_active_bmt.png";
    }

    //termometer
    else if (pageSplit == "grundsfo")
        filename = "guideGrundskoleSfo.aspx";
    else if (pageSplit == "ungvoksen")
        filename = "guideUngVoksen.aspx";
    else if (pageSplit == "benchmarkerterm")
        filename = "guideBenchmarkerTermometeret.aspx";
    else
        return;

    // If dialog already exists, it'll not be reopened, but just ignored.
    var dialogData = {
        name: "GuideDialog",
        type: "close",
        title: "Vejledninger",
        content: "Henter data...",
        width: 720, //670,
        height: "auto",
        maxWidth: 0,
        maxHeight: "70%",
        //        height: "70%",
        //        maxWidth: 0,
        //        maxHeight: 0,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);

    $("#GuideDialog #DialogGuideDialogContent").load(GetRootPath() + "/dialogs/" + filename, null, function () { $("#" + manual).css("display", "inline"); UpdateSizeDialog(dialogData) });

    //$("#" + manual).css("display", "inline");
    //$("#DialogGuideDialogContent").css("display", "inline");
    //UpdateSizeDialog(dialogData);

    //ShowDialog("GuideDialog", "close", "Om Børnemiljøtermometeret", "Henter data...", null, null, null, 670, 500, 0, 0, "true");


    var buttonsHtml = '<table><tr><td><input type="button" class="button" value="Print denne vejledning" onclick="javascript:PrintManual(\'' + pageSplit + '\');" />&nbsp;&nbsp;&nbsp;</td>';
    //buttonsHtml += '<input type="button" class="button" id="Button2" value="Se anden vejledning" onclick="javascript:ShowChooseManualDialog();" />&nbsp;&nbsp;&nbsp;'
    buttonsHtml += '<td><input type="button" class="button" id="Button2" value="Indholdsfortegnelse" onclick="javascript:ShowGuidePage(\'' + pageSplit + '_index\');" />&nbsp;&nbsp;&nbsp;</td>'
    buttonsHtml += '<td><input type="button" class="button" id="OkManualButton" value="Luk vindue" onclick="javascript:CloseDialog(\'GuideDialog\');" /></td>';


    var previousmanual = null;
    var nextmanual = null;
    var counter = 0;
    var current = -1;
    var text = pageSplit + "_";
    $("#[id^=" + text + "]").each(function () {

        var myId = $(this).attr('id');
        if (myId == manual) {
            current = counter;
        }
        counter++;
    });

    if (current > 0) {
        if (current > 1) {
            var elem = $("#[id^='" + text + "']")[current - 1];
            var id = $(elem).attr('id');
            previousmanual = id;
        }
        if (current < $("#[id^='" + text + "']").length) {
            var elem = $("#[id^='" + text + "']")[current + 1];
            var id = $(elem).attr('id');
            nextmanual = id;
        }
    }

    if (previousmanual != null) {
        var imageLink = '<td><a style="padding-left:20px;" href="javascript:ShowGuidePage(\'' + previousmanual + '\');"><img src="' + GetRootPath() + "/" + leftarrowsrc + '" style="border-width:0px;" /></a></td>';
        buttonsHtml += imageLink;
    }
    if (nextmanual != null) {
        var imageLink = '<td><a style="padding-left:20px;" href="javascript:ShowGuidePage(\'' + nextmanual + '\');"><img src="' + GetRootPath() + "/" + rightarrowsrc + '" style="border-width:0px;" /></a></td>';
        buttonsHtml += imageLink;
    }

    $("#ButtonsGuideDialog").css("text-align", "left");
    buttonsHtml += '</tr></table>';
    $("#ButtonsGuideDialog").html(buttonsHtml);
}

function ShowTermsAndConditions() {

    dialogData = {
        name: "TermsAndConditions",
        type: "close", // close, working, yesno, ok
        title: "Vilkår",
        content: "Henter data...",
        callbackYes: null,
        callbackNo: null,
        callbackOKClose: null,
        width: 550,
        height: 400,
        maxWidth: 0,
        maxHeight: 0,
        rightJustifyButtons: true,
        colortheme: null,
        closeWithEscape: true,
        btnArray: null,
        centerVertically: true,
        appendToForm: null,
        putOnTopDocument: false // true/false
    }

    ShowDialogImproved(dialogData);

    //ShowDialog("TermsAndConditions", "close", "Vilkår", "Henter data...", null, null, null, 550, 400, 0, 0, "true");
    //$("#TermsAndConditions #DialogTermsAndConditionsContent").load(GetRootPath() + "/dialogs/termsAndCondition.aspx");

    $("#TermsAndConditions #DialogTermsAndConditionsContent").load(GetRootPath() + "/dialogs/termsAndCondition.aspx", null, function () { UpdateSizeDialog(dialogData) });
}

function ShowBeregningsgrundlag() {
    ShowDialog("Beregningsgrundlag", "close", "Beregningsgrundlag", "Henter data...", null, null, null, 610, 420, 0, 0, "true");
    $("#Beregningsgrundlag #DialogBeregningsgrundlagContent").load(GetRootPath() + "/dialogs/BeregningsgrundlagForPoint.aspx");
}

function ShowVaegtningOgPoint() {
    ShowDialog("VaegtningOgPoint", "close", "Konkret vægtning og tildeling af point", "Henter data...", null, null, null, 610, 420, 0, 0, "true");
    $("#VaegtningOgPoint #DialogVaegtningOgPointContent").load(GetRootPath() + "/dialogs/VaegtningOgPoint.aspx");
}

function ShowBranches(type) {
    var dialogData = {
        name: "ShowBranchesDialog",
        type: "close",
        title: "Underspørgsmål",
        content: "Henter data... Vent venligst",
        width: "80%",
        height: "50%",
        maxWidth: 800,
        maxHeight: 0,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);

    var page = GetSyncPage(GetRootPath() + "/dialogs/showBranches.aspx?type=" + type);
    $("#ShowBranchesDialog #DialogShowBranchesDialogContent").html(page);
}

function ShowBonusList(type) {
    var dialogData = {
        name: "BonusListDialog",
        type: "close",
        title: "Konkrete spørgsmål, der indgår i bonusresultaterne",
        content: "Henter data... Vent venligst",
        width: "70%",
        height: "60%",
        maxWidth: 650,
        maxHeight: 0,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);

    var page = GetSyncPage(GetRootPath() + "/dialogs/bonusList.aspx?type=" + type);
    $("#BonusListDialog #DialogBonusListDialogContent").html(page);
}

function ShowDemoFlash() {
    var page = GetSyncPage(GetRootPath() + "/dialogs/demoInstitutionQuestions.aspx");

    var dialogData = {
        name: "DemoFlashDialog",
        type: "close",
        title: "Oprettelse af egne spørgsmål og svarmuligheder",
        content: page,
        width: 550,
        height: "70%",
        maxWidth: 0,
        maxHeight: 500,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);
}

function ShowBonusBeregningsgrundlag() {
    ShowDialog("Bonusresultater", "close", "Generering af Bonusresultater", "Henter data...", null, null, null, 610, 420, 0, 0, "true");
    $("#Bonusresultater #DialogBonusresultaterContent").load(GetRootPath() + "/dialogs/GenereringAfBonusresultater.aspx");
}

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);
}

// SPEECH -- start

function hentFlashObjekt(flashnavn) {
    if (window.document[flashnavn]) {
        return window.document[flashnavn];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1) {
        if (document.embeds && document.embeds[flashnavn])
            return document.embeds[flashnavn];
    }
    else {
        return document.getElementById(flashnavn);
    }
}

function playsound(value) {
    sendtoflash2('player', value);
}

function sendtoflash2(objname, value) {
    if (hentFlashObjekt(objname) == null)
        return;
    else {
        var flashobjekt = hentFlashObjekt(objname);
        flashobjekt.SetVariable("filename", value);
    }
}


// SPEECH -- slut



function URLEncode(url) //Function to encode URL.
{
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" + // Numeric
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
"abcdefghijklmnopqrstuvwxyz" +
"-_.!~*'()"; // RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";

    var plaintext = url;
    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+"; // x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                alert("Unicode Character '"
+ ch
+ "' cannot be encoded using standard URL encoding.\n" +
"(URL encoding only supports 8-bit characters.)\n" +
"A space (+) will be substituted.");
                encoded += "+";
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    }

    return encoded;
};




function URLDecode(url) //function decode URL
{
    // Replace + with ' '
    // Replace %xx with equivalent character
    // Put [ERROR] in output if %xx is invalid.
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var encoded = url;
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
        var ch = encoded.charAt(i);
        if (ch == "+") {
            plaintext += " ";
            i++;
        } else if (ch == "%") {
            if (i < (encoded.length - 2)
&& HEXCHARS.indexOf(encoded.charAt(i + 1)) != -1
&& HEXCHARS.indexOf(encoded.charAt(i + 2)) != -1) {
                plaintext += unescape(encoded.substr(i, 3));
                i += 3;
            } else {
                alert('Bad escape combination near ...' + encoded.substr(i));
                plaintext += "%[ERROR]";
                i++;
            }
        } else {
            plaintext += ch;
            i++;
        }
    } // while

    return plaintext;
};

function GetLastSplitValue(str) {
    var idSplit = str.split('_');
    return idSplit[idSplit.length - 1];
}

function GetSecondLastSplitValue(str) {
    var idSplit = str.split('_');
    return idSplit[idSplit.length - 2];
}

function GetValuesAsCSV(array) {
    // Tager IKKE hoejde for indhold med kommaer!!!
    var separator = '';
    var str = '';

    for (i = 0; i < array.length; i++) {
        str += separator + array[i];
        separator = ',';
    }

    return str;
}

// ---- GET BROWSER INFO ----------------

function OpenBrowserInfoDialog() {

    var text = getSystemInfo();

    var dialogData = {
        name: "BrowserInfoDialog",
        type: "ok",
        title: "System information",
        content: text,
        width: 500,
        height: 300,
        maxWidth: 0,
        maxHeight: 0,
        rightJustifyButtons: true,
        closeWithEscape: true,
        centerVertically: true,
        putOnTopDocument: true
    }

    ShowDialogImproved(dialogData);
}

// ---- DYNAMIC ADD/REMOVE CSS-FILES ----

//var cssfilesadded = "";  //list of files already added

function checkDynamicLoadCSSfile(filename, allOtherCSSFilesToBeRemoved) {

    for (i = 0; i < allOtherCSSFilesToBeRemoved.length; i++)
        dynamicRemoveCSSFile(allOtherCSSFilesToBeRemoved[i]);

    dynamicLoadCSSfile(filename);

    //    if (cssfilesadded.indexOf("[" + filename + "]") == -1) {
    //        dynamicLoadCSSfile(filename)
    //        cssfilesadded += "[" + filename + "]" //List of files added in the form "[filename1],[filename2],etc"
    //    }
}

function dynamicRemoveCSSFile(filename) {
    var targetelement = "link";
    var targetattr = "href";
    var allsuspects = document.getElementsByTagName(targetelement);
    for (var i = allsuspects.length; i >= 0; i--) { //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
    }
}

function dynamicLoadCSSfile(filename) {
    var fileref = document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", GetRootPath() + "/css/" + filename)

    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

// --------------------------------

function IsTextEmpty(value) {
    if (value == null || value.trim() == '' || value.length == 0)
        return true;

    return false;
}

function OpenSurveyDialog(surveyID) {
    // surveyID can be null

    var html;

    if (surveyID == null)
        html = GetSyncPageNoCache(GetRootPath() + "/dialogs/surveyControlContainer.aspx");
    else
        html = GetSyncPageNoCache(GetRootPath() + "/dialogs/surveyControlContainer.aspx?surveyID=" + surveyID);

    // Just adding a default "close"-button (which will probably be overwritten, because buttons will be added in the usercontrol)...
    var btnArray = new Array();
    var btn;
    var btnNo = 0;

    btn = new Object();
    btn.label = "Luk vindue";
    btn.click = "CloseDialog('SurveyDialog');";
    btnArray[btnNo++] = btn;

    var dialogData = new Object();
    dialogData.name = "SurveyDialog";
    dialogData.type = null;
    dialogData.title = "Undersøgelse";
    dialogData.btnArray = btnArray;
    dialogData.content = html;
    dialogData.width = "90%";
    dialogData.height = "70%";
    dialogData.centerVertically = true;

    ShowDialogImproved(dialogData);

    InitSurveyControlDialog();
}

function ShowForgotPasswordPopup(usernameText, isBenchmarker) {

    var addBenchmarkerParam = false;

    if (typeof isBenchmarker !== 'undefined' && isBenchmarker == true)
        addBenchmarkerParam = true;

    var page;

    if (addBenchmarkerParam)
        page = GetSyncPageNoCache(GetRootPath() + "/dialogs/ForgotPassword.aspx?benchmarker=true");
    else
        page = GetSyncPageNoCache(GetRootPath() + "/dialogs/ForgotPassword.aspx");

    ShowDialog("ForgotPasswordDialog", null, "Send ny adgangskode", page, null, null, null, 550, "auto", 0, 0, "true");
    ForgotPasswordDialogSetUsernameText(usernameText);
}


