﻿var Common =
{
    currentUser: null,
    currentPortal: null,
    currentLCID: null,
    currentServerTime: null,
    twelveHourClock: false,
    employeeFormalNamePattern: "{0} {2}",

    breakToken: {},

    imagesFolder: "/app_themes/version1/images/",
    iconsFolder: "/app_themes/version1/images/icons/",

    toArray: function (iterable) {
        if (!iterable)
            return [];

        if (iterable.toArray)
            return iterable.toArray();

        var length = iterable.length, results = new Array(length);

        while (length--)
            results[length] = iterable[length];

        return results;
    },

    popup:
    {
        getHandler: function () {
            if (window.location.search.indexOf("popup") == -1)
                return GetPopup;

            return GetPopupFromPopup;
        },

        getWindowName: function () {
            if (window.location.search.indexOf("popup") == -1)
                return "PopupWindowControl";

            return "PopupWindowControlMDI";
        }
    },

    translations:
    {
        // Default translations.
        genericErrorTitle: "Fejl",
        genericErrorMessage: "Der opstod desværre en fejl, prøv evt. igen."
    }
}

function getFile(href)
{
    var userAgent = navigator.userAgent.toLowerCase();

    // This will enable smartphones to download the file, the frames[...].location.href does not work here.
    if (userAgent.indexOf("iphone") || userAgent.indexOf("htc") || userAgent.indexOf("android"))
    {
        window.open(href);
    }
    else
    {
        frames["IfmGetter"].location.href = attachmentHref;
    }
}

function getAttachment(portalId, attachmentGuid, attachmentDataType, activePortalId)
{
    try
    {
        var attachmentHref = "/GetAttachment.ashx?portalId=" + portalId + "&guid=" + attachmentGuid;

        if (attachmentDataType != null)
            attachmentHref += "&attachmentDataType=" + attachmentDataType;

        if (activePortalId != null)
            attachmentHref += "&activePortalId=" + activePortalId;


        getFile(attachmentHref);
    }
    catch (err) { }
}

function getPaySlip(payslipGuid, payslipType)
{
    try
    {
        var attachmentHref = "/GetPaySlip.ashx?guid=" + payslipGuid;

        if (payslipType != null)
            attachmentHref += "&payslipType=" + payslipType;

        getFile(attachmentHref);
    }
    catch (err) { }
}

function getInvoice(invoiceGuid)
{
    try
    {
        var attachmentHref = "/GetInvoice.ashx?guid=" + invoiceGuid;

        getFile(attachmentHref);
    }
    catch (err) { }
}

var beforeReloadModuleListeners = [];

function onBeforeReloadModule()
{
    beforeReloadModuleListeners.each(function (listener)
    {
        listener();
    });
}

function GetPopup(url, windowControl, width, height, openMaximized, iconUrl)
{
    var oWnd = radopen(url, windowControl);
    radWindowFixer(oWnd);

    var viewportWidth = 0;
    var viewportHeight = 0;
    var scrollTop = 0;

    if (iconUrl != null)
        setRadWindowIcon(oWnd, iconUrl);

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerWidth != 'undefined')
    {
        viewportWidth = window.innerWidth;
        viewportHeight = window.innerHeight;
        scrollTop = window.pageYOffset;
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
    {
        viewportWidth = document.documentElement.clientWidth;
        viewportHeight = document.documentElement.clientHeight;
        scrollTop = document.documentElement.scrollTop;
    }

    // older versions of IE
    else
    {
        viewportWidth = document.getElementsByTagName('body')[0].clientWidth;
        viewportHeight = document.getElementsByTagName('body')[0].clientHeight;
        scrollTop = document.getElementsByTagName('body')[0].scrollTop;
    }

    // Modify width and height to be within the current viewport.
    if (width > viewportWidth)
        width = viewportWidth - 50;

    if (height > viewportHeight)
        height = viewportHeight - 50;

    // Center popup in viewport.
    var left = (viewportWidth - width) / 2;
    var top = ((viewportHeight - height) / 2) + scrollTop;

    oWnd.setSize(width, height);
    radWindowFixerOnResized(oWnd);
    oWnd.MoveTo(left, top);

    if (openMaximized)
        oWnd.maximize();

    return oWnd;
}

function AlertWindow()
{
    this.radAlertWindow = null;
    this.width = 300;
    this.height = 250;
    this.title = Common.translations.genericErrorTitle;
    this.text = Common.translations.genericErrorMessage;
    this.titleIcon = "sign_warning.png";
    this.hideTextIcon = false;
    this.enableTextScroll = false;
}

AlertWindow.prototype.open = function ()
{
    this.radAlertWindow = radalert(this.text, this.width, this.height, this.title);
    radWindowFixer(this.radAlertWindow);
    setRadWindowTitle(this.radAlertWindow, this.title);
    setRadWindowIcon(this.radAlertWindow, (this.titleIcon.startsWith("/") ? this.titleIcon : Common.iconsFolder + this.titleIcon));
    radWindowFixerOnResized(this.radAlertWindow);

    var jPopupElement = $(this.radAlertWindow.get_popupElement());
    var jDiv = jPopupElement.find("div.rwDialogPopup.radalert");

    if (this.hideTextIcon)
        jDiv.css({ paddingLeft: "0px", backgroundImage: "none" });

    if (this.enableTextScroll)
    {
        var jRadWindow = jDiv.parents("div.RadWindow:first");
        var jTextDiv = jDiv.find("div.rwDialogText");
        var currentPopupHeight = jPopupElement.height();
        var currentDivHeight = jDiv.height();

        //Kmbo.log(currentPopupHeight, currentDivHeight)

        if (currentPopupHeight > this.height)
        {
            jRadWindow.css("height", this.height + "px");
            jTextDiv.css({ overflow: "auto", height: (this.height - 81) + "px" });
        }
    }
}

function OpenAlert(title, message, icon, width, height)
{
    var alertWindow = radalert(message, width, height, title);
    radWindowFixer(alertWindow);
    setRadWindowTitle(alertWindow, title);
    setRadWindowIcon(alertWindow, (icon.startsWith("/") ? icon : Common.iconsFolder + icon));
    radWindowFixerOnResized(alertWindow);
}

function OpenPrompt(title, message, icon, width, height, callback)
{
    var promptWindow = radprompt(message, callback, width, height, null, title);
    radWindowFixer(promptWindow);
    setRadWindowTitle(promptWindow, title);
    setRadWindowIcon(promptWindow, (icon.startsWith("/") ? icon : Common.iconsFolder + icon));
    radWindowFixerOnResized(promptWindow);

    return promptWindow;
}

function OpenConfirm(title, message, icon, width, height, callback)
{
    var confirmWindow = radconfirm(message, callback, width, height, null, title);
    radWindowFixer(confirmWindow);
    setRadWindowTitle(confirmWindow, title);
    setRadWindowIcon(confirmWindow, (icon.startsWith("/") ? icon : Common.iconsFolder + icon));
    radWindowFixerOnResized(confirmWindow);

    return confirmWindow;
}

function OpenPopup(url, windowControl, width, height, openMaximized, iconUrl)
{
    GetPopup(url, windowControl, width, height, openMaximized, iconUrl);
}

function GetPopupFromPopup(url, windowControl, width, height)
{
    var parentWindow = GetRadWindow();
    var parentPage = parentWindow.BrowserWindow;
    var parentRadWindowManager = parentPage.GetRadWindowManager();

    var oWnd2 = parentRadWindowManager.open(url, windowControl);
    radWindowFixer(oWnd2);

    var viewportWidth = 0;
    var viewportHeight = 0;
    var scrollTop = 0;
    var parentDoc = parentPage.document;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof parentPage.innerWidth != 'undefined')
    {
        viewportWidth = parentPage.innerWidth;
        viewportHeight = parentPage.innerHeight;
        scrollTop = parentPage.pageYOffset;
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof parentDoc.documentElement != 'undefined' && typeof parentDoc.documentElement.clientWidth != 'undefined' && parentDoc.documentElement.clientWidth != 0)
    {
        viewportWidth = parentDoc.documentElement.clientWidth;
        viewportHeight = parentDoc.documentElement.clientHeight;
        scrollTop = parentDoc.documentElement.scrollTop;
    }

    // older versions of IE
    else
    {
        viewportWidth = parentDoc.getElementsByTagName('body')[0].clientWidth;
        viewportHeight = parentDoc.getElementsByTagName('body')[0].clientHeight;
        scrollTop = parentDoc.getElementsByTagName('body')[0].scrollTop;
    }

    // Modify width and height to be within the current viewport.
    if (width > viewportWidth)
        width = viewportWidth - 50;

    if (height > viewportHeight)
        height = viewportHeight - 50;

    // Center popup in viewport.
    var left = (viewportWidth - width) / 2;
    var top = ((viewportHeight - height) / 2) + scrollTop;

    oWnd2.setSize(width, height);
    radWindowFixerOnResized(oWnd2);
    oWnd2.MoveTo(left, top);

    return oWnd2;
}

function OpenPopupFromPopup(url, windowControl, width, height)
{
    GetPopupFromPopup(url, windowControl, width, height);
}

// Called when a window is being closed.
function OnClientClose(radWindow, args)
{
    var arg = radWindow.argument;

    if (arg != '' && arg != undefined)
    {
        var argsSplitResult = arg.split("|");
        if (argsSplitResult[0] != '')
        {
            if (argsSplitResult[0] == 'update' && argsSplitResult[1] != '')
            {
                ReloadModule(argsSplitResult[1], argsSplitResult[2]);
            }
            else if (argsSplitResult[0] == "personal.shortcuts.reload")
            {
                // Assume footer is defined for the current page request.
                FooterBarHandler.shortcutsReload();
            }
            else if (argsSplitResult[0] == "courses.online.participation-popup.closed")
            {
                if (Kmbo.SoundPlayer != null)
                {
                    var currentPlayer = Kmbo.SoundPlayer.getCurrent();

                    if (currentPlayer != null)
                        currentPlayer.stopCurrentSound();
                }

                if (radWindow.updateButtonClientId != null)
                {
                    ReloadModule(radWindow.updateButtonClientId, radWindow.popupOpendFromPopup);

                    // Clear settings.
                    radWindow.updateButtonClientId = null;
                    radWindow.popupOpendFromPopup = null;
                }
            }
            else if (argsSplitResult[0] == "courses.online.pagelayouteditor.action")
            {
                if (argsSplitResult.length > 0)
                {
                    if (argsSplitResult[1] == "reload")
                    {
                        if (window["currentPageLayoutEditor"] != null && currentPageLayoutEditor.reloadPage)
                            currentPageLayoutEditor.reloadPage();
                    }
                }
            }
        }
    }
}

function ReloadModule(buttonId, opendFromPopup)
{
    try
    {
        ClickUpdateButton(buttonId, opendFromPopup);
    }
    catch (err)
    {
    }
}

function ClickUpdateButton(buttonID, opendFromPopup)
{
    var objButton;
    if (opendFromPopup == '1')
    {

        if (typeof (frames["PopupWindowControlNoClose"]) != 'undefined')
        {
            objButton = frames["PopupWindowControlNoClose"].document.getElementById(buttonID);
        }

        if (objButton == null && typeof (frames["PopupWindowControl"]) != 'undefined')
        {
            objButton = frames["PopupWindowControl"].document.getElementById(buttonID);
        }

        if (objButton == null && typeof (frames["PopupWindowControlMDI"]) != 'undefined')
        {
            objButton = frames["PopupWindowControlMDI"].document.getElementById(buttonID);
        }

    }

    //If the control wasent found in the popup try and locate it on the main site
    if (objButton == null)
    {
        objButton = document.getElementById(buttonID);
    }

    if (objButton != null)
    {
        onBeforeReloadModule();
        objButton.click();
    }
}

function SetCityName(country, sourceId, targetId)
{
    var zipCodeVal = $get(sourceId).value;

    ZipcodeService.GetCityName(country, zipCodeVal, targetId, onWebServiceComplete, onWebServiceError, onWebServiceTimeOut);
}

function onWebServiceComplete(value)
{
    var values = value.toString().split('|');
    var targetId = values[0];
    var zip = values[1];

    $get(targetId).value = zip;
}

function onWebServiceError(error)
{ }

function onWebServiceTimeOut(error)
{ }

function WriteSuccessMsg(sTitle, sText)
{
    $.gritter.add({ title: sTitle, text: sText, image: '/app_themes/version1/images/icons/48/check.png' });
}

function WriteErrorMsg(sTitle, sText)
{
    $.gritter.add({ title: sTitle, text: sText, image: '/app_themes/version1/images/icons/48/error.png' });
}

if (!String.prototype.trim)
{
    String.prototype.trim = function ()
    {
        return this.replace(/^\s+|\s+$/g, "");
    }
}

if (!String.prototype.endsWith)
{
    String.prototype.endsWith = function (value)
    {
        return (this.match(value + "$") == value);
    }
}

if (!String.prototype.startsWith)
{
    String.prototype.startsWith = function (value)
    {
        return (this.match("^" + value) == value);
    }
}

if (!String.prototype.trimHtml)
{
    String.prototype.trimHtml = function()
    {
        if (this == null || this.length == 0)
            return this;

        var source = this.trim();

        while (source.startsWith("&nbsp;"))
            source = source.substr("&nbsp;".length).trim();

        while (source.endsWith("&nbsp;"))
            source = source.substring(0, source.lastIndexOf("&nbsp;")).trim();

        return source;
    }
}

if (!String.prototype.trimLineBreaks)
{
    String.prototype.trimLineBreaks = function ()
    {
        if (this == null || this.length == 0)
            return this;

        var source = this.trim();

        while (source.startsWith("<br>"))
            source = source.substr("<br>".length).trim();

        while (source.endsWith("<br>"))
            source = source.substring(0, source.lastIndexOf("<br>")).trim();

        while (source.startsWith("<br />"))
            source = source.substr("<br />".length).trim();

        while (source.endsWith("<br />"))
            source = source.substring(0, source.lastIndexOf("<br />")).trim();

        while (source.startsWith("<br/>"))
            source = source.substr("<br/>".length).trim();

        while (source.endsWith("<br/>"))
            source = source.substring(0, source.lastIndexOf("<br/>")).trim();

        return source;
    }
}

if (!String.prototype.isNumeric)
{
    String.prototype.isNumeric = function ()
    {
        return this != null && this.length > 0 && !isNaN(this);
    }
}

if (!String.prototype.parseToInt)
{
    String.prototype.parseToInt = function (radix)
    {
        if (this.isNumeric())
        {
            var parseValue = this;
            
            while (parseValue.length > 0)
            {
                if (parseValue.substr(0, 1) == "0")
                    parseValue = parseValue.substring(1);
                else
                    break;
            }

            if (parseValue.length == 0)
                return 0;

            return parseInt(parseValue, radix);
        }

        return null;
    }
}

if (!String.prototype.parseToFloat)
{
    String.prototype.parseToFloat = function ()
    {
        var replaced = this.replace(/,/g, ".");

        if (replaced.isNumeric())
        {
            var parseValue = replaced;

            if (parseValue.length == 0)
                return 0;

            return parseFloat(parseValue);
        }

        return null;
    }
}

if (!String.prototype.parseToDate)
{
    String.prototype.parseToDate = function ()
    {
        if (this.length == 0)
            return null;

        var prefix = "/Date(";
        var postfix = ")/";

        // Must start with prefix and end with postfix.
        if (this.indexOf(prefix) == 0 && (this.indexOf(postfix) + postfix.length == this.length))
        {
            var ticksValue = this.substring(prefix.length, this.length - postfix.length);

            if (!ticksValue.isNumeric())
                return null;

            var ticks = ticksValue.parseToInt();
            return new Date(ticks);
        }

        return null;
    }
}

if (!String.prototype.parseToLocalDate)
{
    String.prototype.parseToLocalDate = function ()
    {
        if (this.length == 0)
            return null;

        var prefix = "LocalDate(";
        var postfix = ")";

        // Must start with prefix and end with postfix.
        if (this.indexOf(prefix) == 0 && (this.indexOf(postfix) + postfix.length == this.length))
        {
            var value = this.substring(prefix.length, this.length - 1);
            var parts = value.split(",");

            return new Date(parts[0],
                parts[1],
                parts[2],
                parts[3],
                parts[4],
                parts[5]);
        }

        return null;
    }
}

function LocalJavascriptDateTime(instance)
{
    this.Date = null;
    this.Value = null;

    if (typeof(instance) == "string")
    {
        this.Date = instance.parseToLocalDate();
        this.Value = instance;
    }
    else if (instance instanceof Date)
    {
        this.Date = instance;
        this.Value = "LocalDate(".concat(this.Date.getFullYear(), ",", this.Date.getMonth(), ",", this.Date.getDate(), ",", this.Date.getHours(), ",", this.Date.getMinutes(), ",", this.Date.getSeconds(), ")");
    }
    else if (instance != null && instance.Value != null && instance.Value.length > 0)
    {
        this.Date = instance.Value.parseToLocalDate();
        this.Value = instance.Value;
    }
    else if (instance != null && instance.Date != null)
    {
        this.Date = instance.Date;
        this.Value = "LocalDate(".concat(this.Date.getFullYear(), ",", this.Date.getMonth(), ",", this.Date.getDate(), ",", this.Date.getHours(), ",", this.Date.getMinutes(), ",", this.Date.getSeconds(), ")");
    }
}

Function.prototype.bind = function ()
{
    if (arguments.length < 2 && arguments[0] === undefined)
        return this;

    var __method = this;
    var args = Common.toArray(arguments);
    var object = args.shift();

    return function ()
    {
        return __method.apply(object, args.concat(Common.toArray(arguments)));
    }
}

Array.prototype.each = function (iterator, context)
{
    var index = 0;
    iterator = iterator.bind(context);

    try
    {
        this._each(function (value)
        {
            iterator(value, index++);
        });
    }
    catch (e)
    {
        if (e != Common.breakToken)
            throw e;
    }

    return this;
}

Array.prototype._each = function (iterator)
{
    for (var i = 0, length = this.length; i < length; i++)
        iterator(this[i], i);
}

// Use native browser JS 1.6 implementation if available.
if (Array.prototype.forEach)
    Array.prototype._each = Array.prototype.forEach;

if (!Array.prototype.contains)
{
    Array.prototype.contains = function (item)
    {
        return this.indexOf(item) != -1;
    }
}

if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function (item, i)
    {
        i || (i = 0);
        var length = this.length;

        if (i < 0)
            i = length + i;

        for (; i < length; i++)
            if (this[i] === item)
                return i;

        return -1;
    }
}

if (!Array.prototype.remove)
{
    Array.prototype.remove = function (item)
    {
        var i = 0;
        var len = this.length;

        while (i < len)
        {
            if (this[i] === item)
            {
                this.splice(i, 1);
                len--;
            }
            else
            {
                i++;
            }
        }

        return this;
    }
}

if (!Array.prototype.copy)
{
    Array.prototype.copy = function ()
    {
        var shallow = [];

        this.each(function (entry)
        {
            shallow.push(entry);
        });

        return shallow;
    }
}

if (!Array.prototype.first)
{
    Array.prototype.first = function ()
    {
        return this.length != 0 ? this[0] : null;
    }
}

if (!Array.prototype.singleOrNull)
{
    Array.prototype.singleOrNull = function (predicate)
    {
        var i = 0;
        var len = this.length;

        while (i < len)
        {
            if (predicate(this[i], i))
                return this[i];

            i++;
        }

        return null;
    }
}

if (!Array.prototype.where)
{
    Array.prototype.where = function (predicate)
    {
        var output = [];
        var i = 0;
        var len = this.length;

        while (i < len)
        {
            if (predicate(this[i], i))
                output.push(this[i]);

            i++;
        }

        return output;
    }
}

if (!Array.prototype.count)
{
    Array.prototype.count = function (predicate)
    {
        var output = 0;
        var i = 0;
        var len = this.length;

        while (i < len)
        {
            if (predicate(this[i], i))
                output++;

            i++;
        }

        return output;
    }
}

if (!Array.prototype.all)
{
    Array.prototype.all = function (predicate)
    {
        var i = 0;
        var len = this.length;

        while (i < len)
        {
            if (!predicate(this[i], i))
                return false;

            i++;
        }

        return true;
    }
}

if (!Array.prototype.any)
{
    Array.prototype.any = function (predicate)
    {
        return this.singleOrNull(predicate) != null;
    }
}

if (!Array.prototype.last)
{
    Array.prototype.last = function ()
    {
        if (this.length == 0)
            return null;

        return this[this.length - 1];
    }
}

if (!Array.prototype.skip)
{
    Array.prototype.skip = function (itemsToSkip)
    {
        if (this.length < itemsToSkip + 1)
            return [];

        return this.slice(itemsToSkip);
    }
}

if (Date.fromMsTicks == null)
{
    Date.fromMsTicks = function (date)
    {
        var regExp = new RegExp("(\\d+)", "ig");
        var match = regExp.exec(date);

        if (match != null && match.length == 2)
            return new Date(new Number(match[1]));

        return null;
    }
}

/*
Supported settings:

- twelveHourClock: 12 (true) or 24 (false, null) hour clock
- startOfDayTimeAs24: if true, a time of 00:00:00 will be outputted as 24:00(:00), a time of 00:15:00 will NOT.
*/
Date.prototype.toString = function (pattern, settings)
{
    // Default pattern.
    if (pattern == null || pattern == "undefined")
        pattern = "dd-MM-yyyy hh:mm pp";

    var day = this.getDate();
    var dayPadded = (new String(day).length == 1 ? "0" + day : day);

    var month = this.getMonth() + 1;
    var monthPadded = (new String(month).length == 1 ? "0" + month : month);

    var hours = this.getHours();
    var hoursPadded = (new String(hours).length == 1 ? "0" + hours : hours);

    var minutes = this.getMinutes();
    var minutesPadded = (new String(minutes).length == 1 ? "0" + minutes : minutes);

    var seconds = this.getSeconds();
    var secondsPadded = (new String(seconds).length == 1 ? "0" + seconds : seconds);

    var period = "";

    if (settings && settings.twelveHourClock)
    {
        if (hours >= 12)
        {
            period = "PM";

            if (hours > 12)
                hours -= 12;
        }
        else
        {
            period = "AM";

            if (hours == 0)
                hours = "12";
        }

        hoursPadded = hours;
    }

    if (settings && settings.startOfDayTimeAs24 && hours == 0 && minutes == 0 && seconds == 0)
    {
        hoursPadded = "24";
    }

    return pattern.
        replace("dd", dayPadded).
        replace("d", day).
        replace("ss", secondsPadded).
        replace("s", seconds).
        replace("MM", monthPadded).
        replace("M", month).
        replace("yyyy", this.getFullYear()).
        replace("hh", hoursPadded).
        replace("mm", minutesPadded).
        replace("pp", period).trim();
}

Date.prototype.dayMs = 1000 * 60 * 60 * 24;
Date.prototype.hourMs = 1000 * 60 * 60;
Date.prototype.minuteMs = 1000 * 60;

var DateSubType =
{
    day: 3,
    hour: 2,
    minute: 1
}

Date.prototype.diffToString = function (compare, pattern)
{
    var outputPattern = pattern || "hh:mm";
    var msDiff = this.getTime() - compare.getTime();
    var isNegative = false;

    if (msDiff < 0)
    {
        msDiff = -(msDiff);
        isNegative = true;
        //return "00:00";
    }

    var days = 0;

    if (msDiff >= this.dayMs)
    {
        var left = msDiff % this.dayMs
        days = (msDiff - left) / this.dayMs;
        msDiff -= (this.dayMs * days);
    }

    var left = msDiff % this.hourMs;
    var hours = (msDiff - left) / this.hourMs;
    msDiff -= (this.hourMs * hours);

    var left = msDiff % this.minuteMs;
    var minutes = (msDiff - left) / this.minuteMs;

    if (outputPattern.indexOf("d") == -1 && outputPattern.indexOf("dd") == -1)
        hours += (days * 24);

    var daysPadded = (new String(days).length == 1 ? "0" + days : days);
    var hoursPadded = (new String(hours).length == 1 ? "0" + hours : hours);
    var minutesPadded = (new String(minutes).length == 1 ? "0" + minutes : minutes);

    return (isNegative ? "-" : "") + outputPattern.
        replace("dd", daysPadded).
        replace("d", days).
        replace("hh", hoursPadded).
        replace("h", hours).
        replace("mm", minutesPadded).
        replace("m", minutes);
}

function ticksToString(ticks, pattern)
{
    var outputPattern = pattern || "hh:mm";
    var isNegative = false;

    if (ticks < 0)
    {
        ticks = -(ticks);
        isNegative = true;
        //return "00:00";
    }

    var days = 0;

    if (ticks >= this.dayMs)
    {
        var left = ticks % Date.prototype.dayMs
        days = (ticks - left) / Date.prototype.dayMs;
        ticks -= (Date.prototype.dayMs * days);
    }

    var left = ticks % Date.prototype.hourMs;
    var hours = (ticks - left) / Date.prototype.hourMs;
    ticks -= (Date.prototype.hourMs * hours);

    var left = ticks % Date.prototype.minuteMs;
    var minutes = (ticks - left) / Date.prototype.minuteMs;

    if (outputPattern.indexOf("d") == -1 && outputPattern.indexOf("dd") == -1)
        hours += (days * 24);

    var daysPadded = (new String(days).length == 1 ? "0" + days : days);
    var hoursPadded = (new String(hours).length == 1 ? "0" + hours : hours);
    var minutesPadded = (new String(minutes).length == 1 ? "0" + minutes : minutes);

    return (isNegative ? "-" : "") + outputPattern.
        replace("dd", daysPadded).
        replace("d", days).
        replace("hh", hoursPadded).
        replace("h", hours).
        replace("mm", minutesPadded).
        replace("m", minutes);
}

Date.prototype.noTime = function ()
{
    return new Date(this.getFullYear(), this.getMonth(), this.getDate());
}

Date.prototype.equalsDate = function (compare)
{
    var thisNoTime = new Date(this.getFullYear(), this.getMonth(), this.getDate());
    var compareNoTime = new Date(compare.getFullYear(), compare.getMonth(), compare.getDate());

    return thisNoTime.getTime() == compareNoTime.getTime();
}

Date.prototype.withoutSeconds = function ()
{
    return new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), 0, 0);
}

Date.prototype.substract = function (number, type)
{
    return this._change(number, type, false);
}

Date.prototype.add = function (number, type)
{
    return this._change(number, type, true);
}

Date.prototype._change = function (number, type, isAdd)
{
    var ticks = this.getTime();
    var changeTicks = 0;

    if (type == DateSubType.minute)
        changeTicks = this.minuteMs * number;
    else if (type == DateSubType.hour)
        changeTicks = this.hourMs * number;
    else if (type == DateSubType.day)
        changeTicks = this.dayMs * number;
    else
        throw "Type unknown: " + type;

    return new Date(ticks - (isAdd ? -changeTicks : changeTicks));
}

// Matches the Kmbo.NineToFive.Web.Utility.DateTimeRoundingDirection enumeration - do not change values!
var DateTimeRoundDirection =
{
    down: 1,
    up: 2,
    nearest: 3
};

function DateTimeTicks(start, end)
{
    this.ticks = 0;

    if (typeof(start) == "number")
        this.ticks = start;

    if (start instanceof DateTimeTicks)
        this.ticks = start.ticks;

    if (start instanceof Date && end instanceof Date)
        this.ticks = end.getTime() - start.getTime();
}

DateTimeTicks.prototype.substract = function (number, type)
{
    return this._change(number, type, false);
}

DateTimeTicks.prototype.add = function (number, type)
{
    return this._change(number, type, true);
}

DateTimeTicks.prototype._change = function (number, type, isAdd)
{
    var changeTicks = 0;

    if (type == DateSubType.minute)
        changeTicks = 1000 * 60 * number;
    else if (type == DateSubType.hour)
        changeTicks = 1000 * 60 * 60 * number;
    else if (type == DateSubType.day)
        changeTicks = 1000 * 60 * 60 * 24 * number;
    else
        throw "Type unknown: " + type;

    return this.ticks - (isAdd ? -changeTicks : changeTicks);
}

DateTimeTicks.prototype.roundMinutes = function (minuteResolution, dateTimeRoundDirection)
{
    var totalMinutes = Math.round(this.ticks / (1000 * 60));
    this.ticks = totalMinutes * 1000 * 60;
    var modulus = totalMinutes % minuteResolution;

    if (dateTimeRoundDirection == DateTimeRoundDirection.up)
    {
        if (modulus > 0)
            this.ticks = this.add(minuteResolution - modulus, DateSubType.minute);
    }
    else if (dateTimeRoundDirection == DateTimeRoundDirection.nearest)
    {
        var half = Math.floor(minuteResolution / 2);

        if (modulus > half)
            this.ticks = this.add(minuteResolution - modulus, DateSubType.minute);
        else
            this.ticks = this.substract(modulus, DateSubType.minute);
    }
    else // Down.
    {
        if (modulus > 0)
            this.ticks = this.substract(modulus, DateSubType.minute);
    }

    return this.ticks;
}

DateTimeTicks.prototype.getTicks = function ()
{
    return this.ticks;
}

DateTimeTicks.prototype.toString = function (pattern)
{
    // Hours as decimal.
    if (pattern == "hd")
    {
        var decimal = new Number(this.ticks / (1000 * 60 * 60));
        var rounded = decimal.roundDecimal(2);
        return (new String(rounded)).replace(".", ",");
    }

    return ticksToString(this.ticks, pattern);
}

Date.prototype.roundMinutes = function (minuteResolution, dateTimeRoundDirection)
{
    var start = this.noTime();
    var dateTimeTicks = new DateTimeTicks(start, this.withoutSeconds());
    return new Date(start.getTime() + dateTimeTicks.roundMinutes(minuteResolution, dateTimeRoundDirection));
}

if (Number.prototype.roundDecimal == null)
{
    Number.prototype.roundDecimal = function (decimals)
    {
        var power = Math.pow(10, decimals);
        return Math.round(this * power) / power;
    }
}

function EmptyRowContextMenu(sender, eventArgs)
{
    var index = eventArgs.get_itemIndexHierarchical(); // index value
    sender.get_masterTableView().selectItem(sender.get_masterTableView().get_dataItems()[index].get_element(), true);
}

function EmptyRowCreated()
{
}

// Fixes for rad popups
var autoSetPopupIconSrc = "";
var popupLoadingTitle = "Henter...";

function radWindowFixerOnResized(radWindow)
{
    var jPopupElement = $(radWindow.get_popupElement());
    var jTable = $("table", jPopupElement);

    var popupHeight = jPopupElement.outerHeight(true);
    var tableHeight = jTable.outerHeight(true);

    if (tableHeight > popupHeight)
        jPopupElement.css("height", tableHeight + "px");

    $("em", jPopupElement).each(function (index, em)
    {
        var jEm = $(em);
        var jDiv = jEm.parent();

        if (jDiv.is("div"))
        {
            var jCell = jDiv.parent();

            if (jCell.is("td"))
                jDiv.css("width", (jPopupElement.width() - 70) + "px");
        }
    });
}

function radWindowFixerOnLoad(radWindow)
{
    radWindowFixerOnResized(radWindow);
}

function onRadWindowLoad(window)
{
    // Set icon.
    var iconUrl = (autoSetPopupIconSrc != "" ? autoSetPopupIconSrc : window._iconUrl);
    var popupElement = window.get_popupElement();
    var jIcon = $(".rwIcon", popupElement);
    jIcon.css("background-image", "url(" + iconUrl + ")");

    // Re-set title.
    var jTitle = $("div.title-wrapper em", popupElement);
    jTitle.html(window.get_title());
}

function radToolTipFixer(radToolTip)
{
    var popupElement = radToolTip.get_popupElement();

    // Fixes the bottom of the window.
    $("td.rtWrapperBottomLeft, td.rtWrapperBottomCenter, td.rtWrapperBottomRight", popupElement).html("<img src=\"/app_themes/version1/images/Transparent.gif\" width=\"1\" height=\"1\" />");
}

function radWindowFixer(radWindow)
{
    var popupElement = radWindow.get_popupElement();
    radWindow.add_pageLoad(radWindowFixerOnLoad);

    // Fixes the bottom of the window.
    $("td.rwCorner, td.rwFooterCenter", popupElement).html("<img src=\"/app_themes/version1/images/Transparent.gif\" width=\"1\" height=\"1\" />");

    $("em", popupElement).each(function (index, em)
    {
        var jEm = $(em);

        if (!jEm.parent().is("div"))
        {
            jEm.wrap("<div style=\"width: 100px; overflow: hidden;\" class='title-wrapper'/>");
        }

        // Set loading title.
        jEm.html(popupLoadingTitle);
    });

    $("td.rwTitlebar", popupElement).css("height", "auto").addClass("auto-height");

    $(".rwTitlebarControls", popupElement).each(function (index, table)
    {
        var jTable = $(table);

        if (!jTable.parent().is("div"))
            jTable.wrap("<div class=\"rw-title-wrapper\" />");

        var iconUrl = (autoSetPopupIconSrc != "" ? autoSetPopupIconSrc : radWindow._iconUrl);

        if (iconUrl != "")
            jTable.find(".rwIcon").css("background-image", "url(" + iconUrl + ")");
    });
}

function setRadWindowTitle(radWindow, title)
{
    var popupElement = radWindow.get_popupElement();

    $("em", popupElement).each(function (index, em)
    {
        var jEm = $(em);
        jEm.html(title);
    });
}

function setRadWindowIcon(radWindow, iconSrc)
{
    var popupElement = radWindow.get_popupElement();
    $(".rwTitlebarControls", popupElement).each(function (index, table)
    {
        var jTable = $(table);
        jTable.find(".rwIcon").css({ "background-position": "0 0", "background-repeat": "no-repeat", "background-image": "url(" + iconSrc + ")" });
    });
}

function showProgressIndicator()
{
    $("#progressIndicator").parent().show();
}

function hideProgressIndicator()
{
    // Hide delayed preventing a flashing effect if the ajax call was fast.
    window.setTimeout(function () { $("#progressIndicator").parent().hide(); }, 300);
}

function centerProgressIndicator()
{
    var hiddenMode = false;
    var jProgress = $("#progressIndicator");
    var jParent = jProgress.parent();

    if (jParent.css("display") == "none")
    {
        hiddenMode = true;
        jProgress.css("visibility", "hidden");
        jParent.show();
    }

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var documentHeight = $(document).height();
    var documentScrollTop = $(document).scrollTop();
    var progressHeight = jProgress.outerHeight(true);
    var progressWidth = jProgress.outerWidth(true);

    var left = (windowWidth - progressWidth) / 2;
    var top = ((windowHeight - progressHeight) / 2) + documentScrollTop;
    jProgress.css({ top: top + "px", left: left + "px" })

    if (hiddenMode)
    {
        jParent.hide();
        jProgress.css("visibility", "visible");
    }
}

jQuery.fn.extend
({
    removeCss: function (cssName)
    {
        return this.each(function ()
        {
            var curDom = $(this);
            jQuery.grep(cssName.split(","),
                    function (cssToBeRemoved)
                    {
                        curDom.css(cssToBeRemoved, '');
                    });
            return curDom;
        });
    },

    centerInWindow: function ()
    {
        var windowHeight = $(window).height();
        var windowWidth = $(window).width();
        var documentHeight = $(document).height();
        var documentScrollTop = $(document).scrollTop();

        return this.each(function ()
        {
            var curDom = $(this);

            var height = curDom.outerHeight(true);
            var width = curDom.outerWidth(true);

            var left = (windowWidth - width) / 2;
            var top = ((windowHeight - height) / 2) + documentScrollTop;
            curDom.css({ top: top + "px", left: left + "px" })
            
            return curDom;
        });
    }
});

$(centerProgressIndicator);
$(window).resize(centerProgressIndicator);
$(document).scroll(centerProgressIndicator);

$.scrollBarSizes = null;

$.getScrollBarSizes = function ()
{
    if ($.scrollBarSizes != null)
        return $.scrollBarSizes;

    var jDiv = $("<div style=\"position: absolute; top: 0px; left: 0px; width: 100px; height: 100px; overflow: scroll; visibility: hidden;\"></div>");
    $(document.body).append(jDiv);

    var jInner = $("<div style=\"width: 100px; height: 100px;\"></div>");
    jDiv.append(jInner);

    jDiv.scrollLeft(50);
    var leftAfter = jDiv.scrollLeft();

    jDiv.scrollTop(50);
    var topAfter = jDiv.scrollTop();

    $.scrollBarSizes = { height: topAfter, width: leftAfter };

    jDiv.remove();

    return $.scrollBarSizes;
}

function blueWrapperHandler()
{
    $("div.blue-wrapper").each(function (index, div)
    {
        var jDiv = $(div);

        if (!jDiv.hasClass("blue-wrapper-skip"))
        {
            var jTable = jDiv.find("table");

            var cssHeight = jDiv.css("height");

            if (cssHeight != null)
            {
                var parsedHeight = parseInt(cssHeight);

                if (jTable.outerHeight() < parsedHeight)
                    jDiv.removeCss("height");
            }
        }
    });
}

$(blueWrapperHandler);

function onRadToolTipShow(radToolTip)
{
    var jToolTip = $(radToolTip.get_popupElement());

    $("td.rtWrapperTopLeft", jToolTip).html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("td.rtWrapperTopRight", jToolTip).html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");

    $("td.rtWrapperLeftMiddle", jToolTip).html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("td.rtWrapperRightMiddle", jToolTip).html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");

    $("td.rtWrapperBottomLeft", jToolTip).html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("td.rtWrapperBottomCenter", jToolTip).html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("td.rtWrapperBottomRight", jToolTip).html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
}

function fixRadEditor()
{
    $("div.RadEditor.reWrapper td.reWrapper_corner").html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("div.RadEditor.reWrapper td.reWrapper_center.reCenter_top").html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("div.RadEditor.reWrapper td.reWrapper_center.reCenter_bottom").html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("div.RadEditor.reWrapper td.reLeftVerticalSide").html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");
    $("div.RadEditor.reWrapper td.reRightVerticalSide").html("<img height=\"1\" width=\"1\" src=\"/app_themes/version1/images/Transparent.gif\" />");

    $("div.RadEditor.reWrapper > table").each(function (index, table)
    {
        var jTable = $(table);
        var tableHeight = jTable.outerHeight(true);
        var jContentTr = null;

        if (tableHeight != 0)
        {
            jTable.find("tr").each(function (index, tr)
            {
                var jTr = $(tr);
                var jToolBarWrapper = $("td.reToolCell div.reToolbarWrapper", jTr);
                var jToolZone = $("td.reToolZone", jTr);

                if (jToolZone.size() > 0 || jTr.css("display") == "none")
                {
                }
                else if (jToolBarWrapper.size() > 0)
                {
                    tableHeight -= jToolBarWrapper.outerHeight(true);
                    tableHeight -= jToolBarWrapper.find("ul").outerHeight(true);
                }
                else if (jTr.children("td.reContentCell").size() == 0)
                {
                    tableHeight -= jTr.outerHeight(true);
                }
                else
                {
                    jContentTr = jTr;
                }
            });

            // Needed for msie.
            if ($.browser.msie)
                tableHeight -= 2;

            jContentTr.find("td").css("height", tableHeight + "px");
        }
    })
}

//$(fixRadEditor);
var popupIconClicked = false;
var disableAutoSetPopupIcon = $.browser.msie;

function autoSetPopupIcon()
{
    if (disableAutoSetPopupIcon)
        return;

    var jDocument = $(document);

    if (!jDocument.hasClass("auto-set-popup-icon"))
    {
        jDocument.addClass("auto-set-popup-icon");

        jDocument.click(function (event)
        {
            if (!popupIconClicked)
                autoSetPopupIconSrc = "";
        });
    }

    $("div.RadGrid td.imageColumn input[type=image]").each(function (index, input)
    {
        var jImageButton = $(input);

        if (!jImageButton.hasClass("auto-set-popup-icon") && !jImageButton.hasClass("auto-set-popup-icon-ignore"))
        {
            jImageButton.addClass("auto-set-popup-icon");
            var imgSrc = jImageButton.attr("src");

            jImageButton.click(function (event)
            {
                autoSetPopupIconSrc = imgSrc;
                popupIconClicked = true;
            });
        }
        else if (jImageButton.hasClass("auto-set-popup-icon-ignore"))
        {
            jImageButton.mousedown(function (event)
            {
                autoSetPopupIconSrc = "";
                popupIconClicked = false;
            });
        }
    });

    $("a.popup-icon-source").each(function (index, anchor)
    {
        var jAnchor = $(anchor);

        if (!jAnchor.hasClass("auto-set-popup-icon") && !jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            var cssClasses = jAnchor.attr("class").split(" ");
            jAnchor.addClass("auto-set-popup-icon");

            for (var i = 0; i < cssClasses.length; i++)
            {
                var cssClass = cssClasses[i];

                if (cssClass.startsWith("icon-source-"))
                {
                    var imgSrc = Common.iconsFolder + cssClass.substr("icon-source-".length).replace(/-u-/i, "_").replace(/-/, ".");

                    jAnchor.click(function (event)
                    {
                        autoSetPopupIconSrc = imgSrc;
                        popupIconClicked = true;
                    });
                }
            }
        }
    });

    $(".rmLink").each(function (index, anchor)
    {
        var jAnchor = $(anchor);

        if (!jAnchor.hasClass("auto-set-popup-icon") && !jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            jAnchor.addClass("auto-set-popup-icon");
            var imgSrc = jAnchor.find(".rmLeftImage").attr("src");

            jAnchor.click(function (event)
            {
                autoSetPopupIconSrc = imgSrc;
                popupIconClicked = true;
            });
        }
        else if (jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            jAnchor.mousedown(function (event)
            {
                autoSetPopupIconSrc = "";
                popupIconClicked = false;
            });
        }
    });

    $(".rtbWrap").each(function (index, anchor)
    {
        var jAnchor = $(anchor);

        if (!jAnchor.hasClass("auto-set-popup-icon") && !jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            var imgSrc = jAnchor.find(".rtbIcon").attr("src");

            // Sources to ignore.
            if (imgSrc == null || imgSrc == "undefined" ||
                imgSrc.indexOf("arrow_right_") != -1 ||
                imgSrc.indexOf("arrow_left_") != -1)
            {
                jAnchor.addClass("auto-set-popup-icon-ignore");
                return;
            }

            jAnchor.addClass("auto-set-popup-icon");

            jAnchor.click(function (event)
            {
                autoSetPopupIconSrc = imgSrc;
                popupIconClicked = true;
            });
        }
        else if (jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            jAnchor.click(function (event)
            {
                autoSetPopupIconSrc = "";
                popupIconClicked = false;
            });
        }
    });

    $("table.rgMasterTable a").each(function (index, anchor)
    {
        var jAnchor = $(anchor);

        if (jAnchor.hasClass("icon-anchor") && !jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            jAnchor.addClass("auto-set-popup-icon-ignore");
            var imgSrc = jAnchor.find("img").attr("src");

            jAnchor.click(function (event)
            {
                autoSetPopupIconSrc = imgSrc;
                popupIconClicked = true;
            });
        }
        else if (!jAnchor.hasClass("auto-set-popup-icon") || !jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            jAnchor.addClass("auto-set-popup-icon-ignore");

            // Use mousedown because click causes an error.
            jAnchor.mousedown(function (event)
            {
                autoSetPopupIconSrc = "";
                popupIconClicked = false;
            });
        }
        else if (jAnchor.hasClass("auto-set-popup-icon-ignore"))
        {
            jAnchor.click(function (event)
            {
                autoSetPopupIconSrc = "";
                popupIconClicked = false;
            });
        }
    });
}

function savePopupIconSrc(src)
{

}

function onClickConfirm(event, message)
{
    if (!confirm(message))
    {
        var jEvent = jQuery.event.fix(event);
        jEvent.preventDefault();
        jEvent.stopPropagation();

        return false;
    }

    return true;
}

function onRadToolbarButtonConfirm(event, message)
{
    var jEvent = jQuery.event.fix(event);
    var jListItem = $(jEvent.target).parents("li");

    if (jListItem.hasClass("rtbDisabled"))
    {
        jEvent.preventDefault();
        jEvent.stopPropagation();

        return false;
    }

    onClickConfirm(event, message);
}

//$(autoSetPopupIcon);

// Page load listeners is fired by the ASP.NET AJAX engine (on page load and update panel loads).
var pageLoadListeners = [];

// Changes colors of validation error messages. Fired for every page load (added as script in the base page).
function onPageLoad(sender, args)
{
    // Validation and summary color fixes.
    $("div.validation-summery").css("color", "#9b0000");
    $("span.validator").css("color", "#9b0000");

    // Rad grid footer border color fixes.
    var jRgExpandColumns = $("table.rgMasterTable td.rgExpandCol:last");
    jRgExpandColumns.each(function (td, index)
    {
        var jTd = $(this);
        if (jTd.css("border-bottom") != "1px solid #d0d7e5")
            jTd.css("border-bottom", "1px solid #d0d7e5");
    });

    // Rad editor
    fixRadEditor();

    autoSetPopupIcon();

    pageLoadListeners.each(function (listener, index)
    {
        listener();
    });
}

var modalOverlayShowing = false;

$(window).resize(function ()
{
    if (!modalOverlayShowing)
        return;

    showModalOverlay();
});

function showModalOverlay()
{
    var jDiv = $("div.kmbo-modal-overlay");

    if (jDiv.size() == 0)
    {
        jDiv = $("<div class=\"kmbo-modal-overlay\"></div>");
        $(document.body).append(jDiv);
    }

    var viewportWidth = 0;
    var viewportHeight = 0;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
    if (typeof window.innerWidth != 'undefined')
    {
        viewportWidth = window.innerWidth;
        viewportHeight = window.innerHeight;
    }
    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
    else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
    {
        viewportWidth = document.documentElement.clientWidth;
        viewportHeight = document.documentElement.clientHeight;
    }
    // older versions of IE
    else
    {
        viewportWidth = document.getElementsByTagName('body')[0].clientWidth;
        viewportHeight = document.getElementsByTagName('body')[0].clientHeight;
        scrollTop = document.getElementsByTagName('body')[0].scrollTop;
    }

    var jDocument = $(document);

    jDiv.css({ width: jDocument.width() + "px", height: jDocument.height() + "px" });
    jDiv.show();
    modalOverlayShowing = true;
}

function hideModalOverlay()
{
    $("div.kmbo-modal-overlay").hide();
    modalOverlayShowing = false;
}

function richTextDisplayerGallery()
{
    var settingsGal =
    {
        CloseOnBlockClick: true,
        useKeyboardShortcuts: true,
        showImageList: false,
        imageInformationTemplate: '<asp:Localize text="<% $Resources:RichTextEditor, Co3Gallery_Header %>" runat="Server" />'
    };

    jQuery("img.Co3Gallery").CreateGallery(settingsGal);
}

function Hashtable()
{
    this.keys = [];
    this.values = [];
    this.count = 0;

    if (arguments.length > 0)
    {
        Common.toArray(arguments).each(function (item)
        {
            this.set(item[0], item[1]);
        } .bind(this));
    }
}

Hashtable.prototype.containsKey = function (key)
{
    return this.keys.indexOf(key) != -1;
}

Hashtable.prototype.get = function (key)
{
    var index = this.keys.indexOf(key);

    if (index == -1)
        return null;

    return this.values[index];
}

Hashtable.prototype.set = function (key, value)
{
    var index = this.keys.indexOf(key);

    // Insert.
    if (index == -1)
    {
        this.keys.push(key)
        this.values.push(value)
        this.count++;
    }
    // Update.
    else
    {
        this.values[index] = value;
    }
}

Hashtable.prototype.remove = function (key)
{
    var index = this.keys.indexOf(key);

    if (index != -1)
    {
        this.keys.splice(index, 1);
        this.values.splice(index, 1);
        this.count--;
    }
}

Hashtable.prototype.each = function (method)
{
    for (var i = 0; i < this.keys.length; i++)
    {
        method(this.keys[i], this.values[i]);
    }
}

Hashtable.prototype.getCount = function ()
{
    return this.count;
}

Hashtable.prototype.getByIndex = function (index)
{
    return this.values[index];
}

Hashtable.prototype.keys = function ()
{
    return this.keys;
}

Hashtable.prototype.values = function ()
{
    return this.values;
}

var Kmbo =
{
    idMap: new Hashtable(),

    register: function (control)
    {
        this.idMap.set(control.id, control);
    },

    unRegister: function (control)
    {
        this.idMap.remove(control.id, control);
    },

    getControl: function (id)
    {
        return this.idMap.get(id);
    },

    log: function (messages)
    {
        try
        {
            if (window["console"] != null && console.log != null && Function.prototype.bind)
            {
                var wrapper = Function.prototype.call.bind(console.log, console);
                wrapper.apply(console, arguments);
            }
        }
        catch (ex) { }
    },

    logGroup: function (name)
    {
        try
        {
            if (window["console"] != null && console.group != null)
                console.group(name);
        }
        catch (ex) { }
    },

    logGroupEnd: function ()
    {
        try
        {
            if (window["console"] != null && console.groupEnd != null)
                console.groupEnd();
        }
        catch (ex) { }
    }
};

Kmbo.AsyncUpdateEventWrapper =
{
    listeners: [],
    endListeners: [],

    addListener: function (listener)
    {
        if (this.listeners.contains(listener))
            return;

        this.listeners.push(listener);
    },

    removeListener: function (listener)
    {
        this.listeners.remove(listener);
    },

    addEndListener: function (listener)
    {
        if (this.endListeners.contains(listener))
            return;

        this.endListeners.push(listener);
    },

    removeEndListener: function (listener)
    {
        this.endListeners.remove(listener);
    },

    initialize: function ()
    {
        var instance = Sys.WebForms.PageRequestManager.getInstance();
        instance.add_initializeRequest(this.onAsyncInitializeRequest.bind(this));
        instance.add_endRequest(this.onAsyncEndRequest.bind(this));
    },

    onAsyncInitializeRequest: function (sender, args)
    {
        try
        {
            this.listeners.each(function (listener, index)
            {
                listener(sender, args);
            });
        }
        catch (ex) { }
    },

    onAsyncEndRequest: function (sender, args)
    {
        try
        {
            this.endListeners.each(function (listener, index)
            {
                listener(sender, args);
            });
        }
        catch (ex) { }

        if (args.get_error() != undefined)
        {
            var errorMessage;

            if (args.get_response().get_statusCode() == "200")
            {
                errorMessage = args.get_error().message;
            }
            else
            {
                // Error occurred somewhere other than the server page.
                errorMessage = Common.translations.genericErrorMessage;
            }

            args.set_errorHandled(true);

            if (errorMessage.length > 400)
            {
                errorMessage = Common.translations.genericErrorMessage.concat("<br />", "<a href=\"javascript:OpenAlert('", Common.translations.genericErrorTitle, "', '", errorMessage.replace(/'/g, ""), "', 'sign_warning.png', 800, 450);\">Se detaljer</a>");
            }

            WriteErrorMsg(Common.translations.genericErrorTitle, errorMessage);

            // If we have tab strips on the page, set selected tab to current highlited (or the user can't click the tab that mighted caused the error again).
            $("div.RadTabStrip").each(function (index, div)
            {
                var jDiv = $(div);
                var jTabs = jDiv.find("div.rtsLevel ul.rtsUL li.rtsLI");

                if (jTabs.size() > 0)
                {
                    var selectedIndex = null;

                    jTabs.each(function (index, li)
                    {
                        var jLi = $(li);
                        var jAnchor = jLi.find("a.rtsLink");

                        if (jAnchor.hasClass("rtsSelected"))
                        {
                            selectedIndex = index;
                            return;
                        }
                    });

                    if (selectedIndex != null)
                    {
                        var id = jDiv.attr("id");

                        if (id != null && id.length > 0)
                        {
                            try
                            {
                                var tabStrip = $find(jDiv.attr("id"));
                                tabStrip.set_selectedIndex(selectedIndex);
                            }
                            catch (ex)
                            {
                                Kmbo.log(ex);
                            }
                        }
                    }
                }
            });
        }
    }
}

$kmbo = Kmbo.getControl.bind(Kmbo);

(function ($)
{
    $.extend(
    {
        getQueryString: function (name)
        {
            function parseParams()
            {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams();

            return this.queryStringParams[name];
        },
        htmlEncode: function (value)
        {
            return $('<div/>').text(value).html();
        },
        htmlDecode: function (value)
        {
            value = value.replace(/&amp;/g, "&");
            return $('<div/>').html(value).text();
        }
    });
})(jQuery);

function weekSelectorOnUpdateComboBoxItem(comboboxItem, dropDownLine)
{
    var item = dropDownLine.get_item();
    var attributes = item.get_attributes();
    var jTextElement = $(item.get_textElement());

    var html = [];

    html.push("<ul>");
    html.push("<li class='wkSelCol1'>");
    html.push(attributes.getAttribute("Week"));
    html.push("</li>")
    html.push("<li class='wkSelCol2'>");
    html.push(attributes.getAttribute("Dates"));
    html.push("</ul>");

    jTextElement.html(html.join(""));

    var comboBox = item.get_parent();

    if (comboBox.get_value() == item.get_value())
    {
        comboBox.set_selectedItem(item);
        comboBox.set_highlightedItem(item);
        item.highlight();
    }
}
