﻿// JScript File

if (typeof window.ContensisControlsNamespace == "undefined")
{
    window.ContensisControlsNamespace = {};
}
if (typeof (window.ContensisControlsNamespace.Browser) == "undefined" || typeof (window.ContensisControlsNamespace.Browser.Version) == null || window.ContensisControlsNamespace.Browser.Version < 1)
{
    window.ContensisControlsNamespace.Browser = { Version: 1 };
    window.ContensisControlsNamespace.Browser.ParseBrowserInfo = function() {
        this.IsMacIE = (navigator.appName == "Microsoft Internet Explorer") && ((navigator.userAgent.toLowerCase().indexOf("mac") != -1) || (navigator.appVersion.toLowerCase().indexOf("mac") != -1));
        this.IsChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
        if (!this.IsChrome) {
            this.IsSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != -1);
        }
        this.IsMozilla = window.netscape && !window.opera;
        if (this.IsMozilla) {
            if (window.showModalDialog) {
                this.IsFirefox3 = true;
            }
            else {
                this.IsFirefox3 = false;
            }
        }
        this.IsNetscape = /Netscape/.test(navigator.userAgent);
        this.IsOpera = window.opera;
        this.IsOpera9 = window.opera && (parseInt(window.opera.version()) > 8);
        this.IsIE = !this.IsMacIE && !this.IsMozilla && !this.IsOpera && !this.IsSafari && !this.IsChrome;
        this.IsIE7 = /MSIE 7/.test(navigator.appVersion);
        this.IsIE8 = /MSIE 8/.test(navigator.appVersion);
        this.IsIE7OrAbove = false;
        if ((this.IsIE7) || (this.IsIE8)) {
            this.IsIE7OrAbove = true;
        }
        this.StandardsMode = this.IsSafari || this.IsOpera9 || this.IsMozilla || document.compatMode == "CSS1Compat";
        this.IsMac = /Mac/.test(navigator.userAgent);

        this.EditorClass = '';
        if (this.IsOpera) { this.EditorClass = 'sys_browser_opera'; }
        if (this.IsMozilla) { this.EditorClass = 'sys_browser_firefox'; }
        if (this.IsMacIE) { this.EditorClass = 'sys_browser_macie'; }
        if (this.IsSafari) { this.EditorClass = 'sys_browser_safari'; }
        if (this.IsIE) { this.EditorClass = 'sys_browser_ie'; }

        if (this.IsOpera9) { this.EditorClass += ' sys_browser_opera9'; }
        if (this.IsFirefox3) { this.EditorClass += ' sys_browser_firefox3' }
        if (this.IsIE) {
            if (!this.IsIE7OrAbove) { this.EditorClass += ' sys_browser_ie6'; }
            if (this.IsIE7) { this.EditorClass += ' sys_browser_ie7'; }
            if (this.IsIE8) { this.EditorClass += ' sys_browser_ie8'; }
        }

        this.DialogSupport = false;
        if (window.showModalDialog) { this.DialogSupport = true; }        
        if (this.IsChrome) { this.DialogSupport = false; }
        //if (this.IsSafari) { this.DialogSupport = false; }
        this.IsTrusted = true;
        try {
            var vis = window.statusbar.visible;
            window.statusbar.visible = false;
            window.statusbar.visible = true;
            window.statusbar.visible = vis;
        }
        catch (ex) { this.IsTrusted = false; }
    };
    ContensisControlsNamespace.Browser.ParseBrowserInfo();
}

//Standard Utils
function Utilities() {
    this.Overlay = null
    this.Querystring = null
    this.popupID = null
    this.isPopup = null
    this.Launching = false;
}

Utilities.prototype.RefreshProjects = Utilities_RefreshProjects;
Utilities.prototype.UrlEncode = Utilities_UrlEncode;
Utilities.prototype.UrlDecode = Utilities_UrlDecode;
Utilities.prototype.GetEventSrcElement = _GetEventSrcElement;
Utilities.prototype.AddEvent = _AddEvent;
Utilities.prototype.RemoveEvent = _RemoveEvent;
Utilities.prototype.KillEvent = _KillEvent;
Utilities.prototype.CancelEventSafari = _CancelEventSafari;
Utilities.prototype.Trim = _Trim;
Utilities.prototype.GetElementsByClassName = _GetElementsByClassName;
Utilities.prototype.HasClassName = _HasClassName;
Utilities.prototype.SubtractWeeks = _SubtractWeeks;
Utilities.prototype.SubtractDays = _SubtractDays;
Utilities.prototype.ResetToStartOfDay = _ResetToStartOfDay;
Utilities.prototype.ResetToEndOfDay = _ResetToEndOfDay;
Utilities.prototype.GetDateForDotNet = _GetDateForDotNet;
Utilities.prototype.IsUndefined = _IsUndefined
Utilities.prototype.IsUndefinedOrNull = _IsUndefinedOrNull
Utilities.prototype.TrimEnd = _TrimEnd
Utilities.prototype.FindCursor = Utilities_FindCursor
Utilities.prototype.FindElementPosition = Utilities_FindElementPosition
Utilities.prototype.AddBodyScript = Utilities_AddBodyScript
Utilities.prototype.ShowFullScreenOverlay = Utilities_ShowFullScreenOverlay
Utilities.prototype.HideFullScreenOverlay = Utilities_HideFullScreenOverlay
Utilities.prototype.OnOverlayClick = Utilities_OnOverlayClick
Utilities.prototype.GetUrlParam = Utilities_GetUrlParam
Utilities.prototype.QueryString = Utilities_QueryString
Utilities.prototype.IsPopup = Utilities_IsPopup
Utilities.prototype.SetPopupID = Utilities_SetPopupID
Utilities.prototype.PopupID = Utilities_PopupID
Utilities.prototype.ReloadPage = Utilities_ReloadPage
Utilities.prototype.OnOverlayContextMenu = Utilities_OnOverlayContextMenu
Utilities.prototype.GetDocument = Utilities_GetDocument
Utilities.prototype.FixFileName = Utilities_FixFileName
Utilities.prototype.RefreshPage = Utilities_RefreshPage;
Utilities.prototype.RemoveHashFromUrl = Utilities_RemoveHashFromUrl;
Utilities.prototype.IsInArray = Utilities_IsInArray;
Utilities.prototype.AppendQueryToUrl = Utilities_AppendQueryToUrl;
Utilities.prototype.DisableWindow = Utilities_DisableWindow;
Utilities.prototype.RegisterTextBoxPopulation = Utilities_RegisterTextBoxPopulation;
Utilities.prototype.RegisterTextBoxPopulationNoStrip = Utilities_RegisterTextBoxPopulationNoStrip;
Utilities.prototype.PopulateTextBoxes = Utilities_PopulateTextBoxes;
Utilities.prototype.PopulateTextBoxes = Utilities_PopulateTextBoxes;
Utilities.prototype.EndsWith = Utilities_EndsWith;
Utilities.prototype.GetParentElementWithClassName = Utilities_GetParentElementWithClassName;
Utilities.prototype.RaisePostback = Utilities_RaisePostback;
Utilities.prototype.SaveCurrentEditor = Utilities_SaveCurrentEditor;
Utilities.prototype.AppendOrReplaceQuerystring = Utilities_AppendOrReplaceQuerystring;

Utilities.prototype.CreateDelegate = _Utilities_CreateDelegate;
Utilities.prototype.AddHandler = _Utilities_AddHandler;
Utilities.prototype.RemoveHandler = _Utilities_RemoveHandler;

Utilities.prototype.RegisterGlobalObject = _Utilities_RegisterGlobalObject;
Utilities.prototype.GetGlobalObject = _Utilities_GetGlobalObject;
Utilities.prototype.RegisterExpandoProperty = _Utilities_RegisterExpandoProperty;
Utilities.prototype.ClearExpandoProperties = _Utilities_ClearExpandoProperties;
Utilities.prototype.RegisterElements = _Utilities_RegisterElements;
Utilities.prototype.ClearElements = _Utilities_ClearElements;
Utilities.prototype.CloseWindow = _Utilities_CloseWindow;
Utilities.prototype.Destroy = _Utilities_Destroy;
Utilities.prototype.BuildListItems = _Utilities_BuildListItems;
Utilities.prototype.EscapeStringForRegEx = Utilities_EscapeStringForRegEx;
Utilities.prototype.DoConfirm = Utilities_DoConfirm;

function Utilities_RefreshProjects() {
    if (window.top.ContensisControlsNamespace)
    {
        if (window.top.ContensisControlsNamespace.ToolbarUI_ProjectsToolbar)
        {
            window.top.ContensisControlsNamespace.ToolbarUI_ProjectsToolbar.RefreshTools()
        }
    }
}

function Utilities_RaisePostback(ControlId, EventName) {
    __doPostBack(ControlId, EventName)
}

function Utilities_GetParentElementWithClassName(Element, ClassName) {
    ClassName = ClassName.toLowerCase()
    if (Element)
    {
        while (null != Element)
        {
            if (this.HasClassName(Element, ClassName))
            {
                return Element
            } else
            {
                Element = Element.parentNode;
            }
        }
    }
    return null
}

function Utilities_AppendQueryToUrl(Url, QueryName, QueryValue) {
    Url = this.RemoveHashFromUrl(Url)
    var Divider = "?";
    if (Url.indexOf('?') > 0)
    {
        Divider = "&"
    }
    Url += Divider + QueryName + "=" + QueryValue
    return Url
}
function Utilities_IsInArray(ArrayOfItems, Item) {
    if (ArrayOfItems)
    {
        for (var i = 0; i < ArrayOfItems.length; i++)
        {
            var tempItem = ArrayOfItems[i]
            if (tempItem == Item)
            {
                return true;
            }
        }
    }
    return false;
}
function Utilities_RemoveHashFromUrl(url) {
    if (url.indexOf('#') > 0)
    {
        url = url.substring(0, url.indexOf('#'));
    }
    return url;
}

function Utilities_UrlEncode(value) {
    // 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 = value;
    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);
            }
        }
    } // for
    return encoded;
}

function Utilities_UrlDecode(value) {
    // Replace + with ' '
    // Replace %xx with equivalent character
    // Put [ERROR] in output if %xx is invalid.
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var encoded = value
    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
    value = plaintext;
    return false;
}

function Utilities_ReloadPage(performSubmit) {
    var reloadPage = false;
    if (!performSubmit) {
        if (document.getElementById('__ContensisDialogueState')) {
            if (document.getElementById('__ContensisDialogueState').value == 'reload') {
                reloadPage = true;
            }
        }
        else {
            reloadPage = true;
        }
    }
    if (!reloadPage)
    {
        try { document.forms[0].submit(); }
        catch (e) { reloadPage = true; }
    }
    if (reloadPage)
    {
        var rnd = Math.ceil(Math.random() * 1000)
        document.location.href = this.AppendQueryToUrl(document.location.href, "rnd", rnd);        
    }
}

function Utilities_RefreshPage(seconds) {
    setInterval("ContensisControlsNamespace.Utilities.ReloadPage()", seconds * 1000);
}

function Utilities_SetPopupID() {
    if (!this.IsUndefinedOrNull(this.popupID))
    {
        return
    }
    var Popupid = ContensisControlsNamespace.Utilities.GetUrlParam('Popupid');
    if (Popupid.length > 0)
    {
        this.popupID = Popupid
        this.isPopup = true
    } else
    {
        this.popupID = ''
        this.isPopup = false
    }
}

function Utilities_IsPopup() {
    this.SetPopupID()
    return this.isPopup
}
function Utilities_PopupID() {
    this.SetPopupID()
    return this.popupID
}

function Utilities_QueryString() {
    if (this.IsUndefinedOrNull(this.Querystring))
    {
        this.Querystring = new QueryStringObject()
    }
    return this.Querystring
}
function Utilities_GetUrlParam(name) {
    var param = this.QueryString().item(name)
    if (!this.IsUndefinedOrNull(param))
    {
        return param.value
    } else
    {
        return '';
    }
}

function Utilities_OnOverlayClick(e) {
    if (ContensisControlsNamespace.Global.CurrentModal)
    {
        ContensisControlsNamespace.Global.CurrentModal.Show()
    }
}

function Utilities_OnOverlayContextMenu(e) {
    window.ContensisControlsNamespace.Utilities.ShowFullScreenOverlay()
    //    if(ContensisControlsNamespace.Global.CurrentModal){          
    //      ContensisControlsNamespace.Global.CurrentModal.Show()       
    //}
    //alert('');
    return false;
}

//This is deprecated and should be removed.
function Utilities_DisableWindow() {
    this.Overlay = document.createElement('div');
    this.Overlay.className = "sys_overlay";
    document.body.appendChild(this.Overlay);
    window.ContensisUtility.RegisterHTMLProperty(this, 'Overlay');
    try { this.Overlay.focus(); }
    catch (e) { }
    // }
}
function Utilities_ShowFullScreenOverlay(message, left, top, width, height) {
    this.HideFullScreenOverlay(true);
    this.Launching = false;
    if (this.IsUndefinedOrNull(message))
    {
        message = ''
    }

    if (typeof (left) == 'undefined')
    {
        if (this.Overlay == null)
        {
            this.Overlay = document.createElement('div');
            this.Overlay.className = "sys_overlay";
            document.body.appendChild(this.Overlay);
            window.ContensisUtility.RegisterHTMLProperty(this, 'Overlay');

            this.OverlayLoadingTextPanel = document.createElement('div');
            this.OverlayLoadingTextPanel.className = 'sys_loading_panel'
            document.body.appendChild(this.OverlayLoadingTextPanel);

            var loadingImage = document.createElement('div');
            loadingImage.className = 'sys_loading_image'
            this.OverlayLoadingTextPanel.appendChild(loadingImage)

            this.OverlayLoadingText = document.createElement('div');
            this.OverlayLoadingText.className = "sys_loading_text";
            this.OverlayLoadingTextPanel.appendChild(this.OverlayLoadingText)

            window.ContensisUtility.RegisterHTMLProperty(this, 'OverlayLoadingText');
            window.ContensisUtility.RegisterHTMLProperty(this, 'OverlayLoadingTextPanel');
            //OnOverlayClick
            window.ContensisUtility.AddEvent(this.Overlay, 'click', this.OnOverlayClick, false)
        }
        if (message.length == 0)
        {
            window.ContensisUtility.setInnerHTML(this.OverlayLoadingText, 'Please Wait...')
        } else
        {
            window.ContensisUtility.setInnerHTML(this.OverlayLoadingText, message)
        }
        this.OverlayLoadingTextPanel.style.display = 'block';
        this.Overlay.style.display = 'block';
        try { this.Overlay.focus(); }
        catch (e) { }
    }
    else
    {
        var fullHeight = 0;
        var fullWidth = 0;
        if (window.innerHeight)
        {
            fullHeight = window.innerHeight;
            fullWidth = window.innerWidth;
        }
        else
        {
            fullHeight = document.body.offsetHeight;
            fullWidth = document.body.offsetWidth;
        }
        if (!this.TopOverlay)
        {
            this.TopOverlay = document.createElement('div');
            this.TopOverlay.className = 'sys_overlay_nospinner';
            window.ContensisUtility.AddEvent(this.TopOverlay, 'click', this.OnOverlayClick, false)
            this.LeftOverlay = document.createElement('div');
            this.LeftOverlay.className = 'sys_overlay_nospinner';
            window.ContensisUtility.AddEvent(this.LeftOverlay, 'click', this.OnOverlayClick, false)
            this.RightOverlay = document.createElement('div');
            this.RightOverlay.className = 'sys_overlay_nospinner';
            window.ContensisUtility.AddEvent(this.RightOverlay, 'click', this.OnOverlayClick, false)
            this.BottomOverlay = document.createElement('div');
            this.BottomOverlay.className = 'sys_overlay_nospinner';
            window.ContensisUtility.AddEvent(this.BottomOverlay, 'click', this.OnOverlayClick, false)
            document.body.appendChild(this.TopOverlay);
            document.body.appendChild(this.LeftOverlay);
            document.body.appendChild(this.RightOverlay);
            document.body.appendChild(this.BottomOverlay);
            window.ContensisUtility.RegisterHTMLProperty(this, 'TopOverlay');
            window.ContensisUtility.RegisterHTMLProperty(this, 'LeftOverlay');
            window.ContensisUtility.RegisterHTMLProperty(this, 'RightOverlay');
            window.ContensisUtility.RegisterHTMLProperty(this, 'BottomOverlay');
        }
        try
        {
            this.TopOverlay.style.top = '0px';
            this.TopOverlay.style.left = '0px';
            this.TopOverlay.style.width = fullWidth + 'px';
            this.TopOverlay.style.height = top + 'px';
            this.TopOverlay.style.display = 'block';
        }
        catch (e)
        {
            this.TopOverlay.style.display = 'none';
        }
        try
        {
            this.LeftOverlay.style.top = top + 'px';
            this.LeftOverlay.style.left = '0px';
            this.LeftOverlay.style.width = left + 'px';
            this.LeftOverlay.style.height = height + 'px';
            this.LeftOverlay.style.display = 'block';
        }
        catch (e)
        {
            this.LeftOverlay.style.display = 'none';
        }

        try
        {
            this.RightOverlay.style.top = top + 'px';
            this.RightOverlay.style.left = (left + width) + 'px';
            this.RightOverlay.style.width = fullWidth - (left + width) + 'px';
            this.RightOverlay.style.height = height + 'px';
            this.RightOverlay.style.display = 'block';
        }
        catch (e)
        {
            this.RightOverlay.style.display = 'none';
        }

        try
        {
            this.BottomOverlay.style.top = top + height + 'px';
            this.BottomOverlay.style.left = '0px';
            this.BottomOverlay.style.width = fullWidth + 'px';
            this.BottomOverlay.style.height = fullHeight - (top + height) + 'px';
            this.BottomOverlay.style.display = 'block';
        }
        catch (e)
        {
            this.BottomOverlay.style.display = 'none';
        }
    }
}
function Utilities_HideFullScreenOverlay(ignoreMoveMode) {
    if (this.IsUndefinedOrNull(ignoreMoveMode))
    {
        ignoreMoveMode = false
    }
    if (this.Overlay != null)
    {
        this.Overlay.style.display = 'none';
        this.OverlayLoadingTextPanel.style.display = 'none';
    }
    if (this.TopOverlay != null)
    {
        this.TopOverlay.style.display = 'none';
        this.LeftOverlay.style.display = 'none';
        this.RightOverlay.style.display = 'none';
        this.BottomOverlay.style.display = 'none';
    }

    //Reenable the overlay if move mode is on in the navigator
    if (!ignoreMoveMode)
    {
        if (ContensisControlsNamespace)
        {
            if (ContensisControlsNamespace.TreeviewNavigator)
            {
                ContensisControlsNamespace.TreeviewNavigator.ResetMoveModeOverlay()
            }
        }
    }
}

Utilities.prototype.UpdateOverlayMessage = function(message) {
    if (message)
    {
        window.ContensisUtility.setInnerHTML(this.OverlayLoadingText, message);
    }
}

function Utilities_ShowWindowOverlay() {
    this.TopOverlay = document.createElement('div');
    this.TopOverlay.style.backgroundColor = 'red';
    document.body.appendChild(this.TopOverlay);

    this.TopOverlay.style.display = 'block';
    window.ContensisUtility.RegisterHTMLProperty(this, 'TopOverlay');
}

function Utilities_HideWindowOverlay() {
    if (this.TopOverlay != null)
    {
        this.TopOverlay.style.display = 'none';
    }
}

function Utilities_AddBodyScript(ScriptText) {
    eval(ScriptText)
}
function Utilities_FindElementPosition(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent)
    {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent)
        {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}
function Utilities_FindCursor(evt) {
    var XY = new Array();
    XY[0] = null;
    XY[1] = null;
    if (typeof evt != "undefined")
    {
        if (evt.pageX)
        {
            XY[0] = evt.pageX;
            XY[1] = evt.pageY;
        } else
        {
            if (evt.clientX)
            {
                XY[0] = evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
                XY[1] = evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
            }
        }
    } else
    {
        if (typeof window.event != "undefined")
        {
            XY[0] = event.clientX;
            XY[1] = event.clientY;
        }
    }
    return XY;
}

function Utilities_GetDocument(Element) {
    if (Element.document)
    {
        return Element.document
    } else
    {
        return Element.ownerDocument
    }
}

function Utilities_FixFileName(filename, useNotPreferred, replaceSpaceWith) {
    var stringExp = this.UnsafeFilenameExpression;
    if (useNotPreferred)
    {
        stringExp = this.NotPreferredFilenameExpression;
    }
    if (replaceSpaceWith)
    {
        filename = filename.replace(/ /ig, replaceSpaceWith);
    }
    else
    {
        filename = filename.replace(/ /ig, '');
    }
    if (stringExp)
    {
        if (typeof (filename) != 'string')
        {
            alert("Filenames must be passed as a string");
        }
        var regEx = new RegExp(stringExp, 'gi');
        return filename.replace(regEx, '');
    }
    else
    {
        alert("Chars not implemented");
    }
    return '';

    // EXits here !!!!!!!!!!!!!!!!
    if (this.UnsafeFilenameExpression)
    {
        if (typeof (filename) != 'string')
        {
            alert("Filenames must be passed as a string");
        }
        if (!this.UnsafeFilenameExpressionRegExp)
        {
            this.UnsafeFilenameExpressionRegExp = new RegExp(this.UnsafeFilenameExpression, 'gi');
        }
        return filename.replace(this.UnsafeFilenameExpressionRegExp, "");
    } else
    {
        alert("Chars not implemented");
    }
    return "";
}

function Utilities_RegisterTextBoxPopulation() {
    if (arguments.length >= 0)
    {
        var exitBox = document.getElementById(arguments[0]);
        if (exitBox)
        {
            exitBox.StripBoxes = [];
            exitBox.InitialValue = exitBox.value;
            exitBox.UseNotPreferred = arguments[1];
            exitBox.ReplaceSpace = arguments[2];
            for (var i = 3; i < arguments.length; i++)
            {
                if (typeof (exitBox.nextBox) == 'undefined')
                {
                    exitBox.nextBox = document.getElementById(arguments[i]);
                }
                exitBox.StripBoxes[exitBox.StripBoxes.length] = document.getElementById(arguments[i]);
            }
            if (typeof (exitBox.PopulateBoxes) == 'undefined')
            {
                window.ContensisUtility.AddEvent(exitBox, 'blur', Utilities_PopulateTextBoxes, false);
                window.ContensisUtility.AddEvent(exitBox, 'keyup', Utilities_PopulateTextBoxesFromKey, false);
            }
        }
    }
}

function Utilities_RegisterTextBoxPopulationNoStrip() {
    if (arguments.length >= 0)
    {
        var exitBox = document.getElementById(arguments[0]);
        if (exitBox)
        {
            exitBox.PopulateBoxes = [];
            exitBox.UseNotPreferred = arguments[1];
            for (var i = 2; i < arguments.length; i++)
            {
                if (typeof (exitBox.nextBox) == 'undefined')
                {
                    exitBox.nextBox = document.getElementById(arguments[i]);
                }
                exitBox.PopulateBoxes[exitBox.PopulateBoxes.length] = document.getElementById(arguments[i]);
            }
            if (typeof (exitBox.StripBoxes) == 'undefined')
            {
                window.ContensisUtility.AddEvent(exitBox, 'blur', this.PopulateTextBoxes, false);
                window.ContensisUtility.AddEvent(exitBox, 'keyup', Utilities_PopulateTextBoxesFromKey, false);
            }
        }
    }
}
function Utilities_PopulateTextBoxesFromKey(e) {
    Utilities_PopulateTextBoxes(e, true)
}
function Utilities_PopulateTextBoxes(e, DoneKeyPress) {
    //alert('hello');
    var box = ContensisControlsNamespace.Utilities.GetEventSrcElement(e);
    if (box)
    {
        if (box.StripBoxes)
        {
            for (var i = 0; i < box.StripBoxes.length; i++)
            {
                var childBox = box.StripBoxes[i];
                if (childBox)
                {
                    var ModifiedByUser = true
                    var NewValue = ContensisControlsNamespace.Utilities.FixFileName(box.value, box.UseNotPreferred, box.ReplaceSpace);
                    if (childBox.value == '')
                    {
                        ModifiedByUser = false
                    }
                    if (childBox.ComputedValue)
                    {
                        if (childBox.ComputedValue == childBox.value)
                        {
                            ModifiedByUser = false
                        }
                    }
                    if (NewValue == childBox.value)
                    {
                        ModifiedByUser = false
                    }
                    if (box.InitialValue)
                    {
                        var initalvaluereplaced = ContensisControlsNamespace.Utilities.FixFileName(box.InitialValue)
                        if (initalvaluereplaced == childBox.value)
                        {
                            ModifiedByUser = false
                        }
                    }
                    if (!ModifiedByUser)
                    {
                        childBox.value = NewValue;
                        childBox.ComputedValue = NewValue
                    }
                }
            }
        }
        if (box.PopulateBoxes)
        {
            for (var i = 0; i < box.PopulateBoxes.length; i++)
            {
                var childBox = box.PopulateBoxes[i];
                if (childBox)
                {
                    var ModifiedByUser = true
                    if (childBox.value == '')
                    {
                        ModifiedByUser = false
                    }
                    if (childBox.ComputedValue)
                    {
                        if (childBox.ComputedValue == childBox.value)
                        {
                            ModifiedByUser = false
                        }
                    }
                    if (box.value == childBox.value)
                    {
                        ModifiedByUser = false
                    }
                    if (box.InitialValue)
                    {
                        if (box.InitialValue == childBox.value)
                        {
                            ModifiedByUser = false
                        }
                    }
                    if (!ModifiedByUser)
                    {
                        childBox.value = box.value;
                        childBox.ComputedValue = box.value;
                    }
                }
            }
        }
        if (box.nextBox)
        {
            if (DoneKeyPress)
            {
                //dont select!
            } else
            {
                box.nextBox.select();
                box.nextBox.focus();
            }
        }
    }
}

function Utilities_EndsWith(StringToSearch, pattern) {
    var d = StringToSearch.length - pattern.length;
    return d >= 0 && StringToSearch.lastIndexOf(pattern) === d;
}

function Utilities_AppendOrReplaceQuerystring(url, QueryStringName, QueryStringvalue) {
    var Url = new String(url)
    var queryStringName = new String(QueryStringName)
    if (Url.indexOf("?") > -1)
    {
        var posfound = Url.toLowerCase().indexOf(QueryStringName.toLowerCase() + "=")
        if (posfound == -1)
        {
            return url + '&' + QueryStringName + "=" + QueryStringvalue
        } else
        {
            var returnval
            var tempstr = new String(url)
            var valuestartpos = posfound + queryStringName.length + 1
            tempstr = tempstr.substring(valuestartpos, tempstr.length)

            var endpos = tempstr.indexOf("&")
            returnval = Url.substring(0, valuestartpos)
            returnval += QueryStringvalue
            if (endpos > -1)
            {
                tempstr = tempstr.substring(endpos, tempstr.length)
                returnval += tempstr
            }
            return returnval
        }
    } else
    {
        return url + '?' + QueryStringName + "=" + QueryStringvalue
    }
}

function _IsUndefined(value) {
    if (typeof (value) == 'undefined')
    {
        return true;
    }
    return false
}
function _IsUndefinedOrNull(value) {
    if (typeof (value) == 'undefined')
    {
        return true;
    }
    if (value == null)
    {
        return true;
    }
    return false
}
function _TrimEnd(value, character) {
    if (value.lastIndexOf(character) == (value.length - 1))
    {
        value = value.substring(0, value.length - 1)
    }
    return value
}
function _GetEventSrcElement(eventElement) {
    if (eventElement.srcElement)
    {
        return eventElement.srcElement
    }
    // Netscape and Firefox
    else if (eventElement.target)
    {
        return eventElement.target
    }
}

function _AddEvent(element, eventType, lamdaFunction, useCapture) {
    if (typeof (this.Events) == 'undefined')
    {
        this.Events = new Array();
    }
    try
    {
        if (element.addEventListener)
        {
            element.addEventListener(eventType, lamdaFunction, useCapture);
            this.Events[this.Events.length] = { element: element, eventType: eventType, lamdaFunction: lamdaFunction, useCapture: useCapture };
            return true;
        } else if (element.attachEvent)
        {
            var r = element.attachEvent('on' + eventType, lamdaFunction);
            this.Events[this.Events.length] = { element: element, eventType: eventType, lamdaFunction: lamdaFunction, useCapture: useCapture };
            return r;
        } else
        {
            return false;
        }
    } catch (e)
    {
        window.status = 'Event issue!'
    }
}

function _RemoveEvent(elm, evType, fn, useCapture) {
    if (elm.removeEventListener)
    {
        elm.removeEventListener(evType, fn, useCapture);
        return true;
    } else if (elm.detachEvent)
    {
        var r = elm.detachEvent("on" + evType, fn);
        return r;
    } else
    {
        alert("Handler could not be removed");
    }
}

function _KillEvent(eventObject) {
    if (eventObject)
    {
        if (eventObject.stopPropagation) eventObject.stopPropagation();
        if (eventObject.preventDefault) eventObject.preventDefault();
        eventObject.returnValue = false;
        eventObject.cancel = true;
        eventObject.cancelBubble = true;
    }

    if (window.event)
    {
        window.event.returnValue = false;
        window.event.cancelBubble = true;
        window.event.cancel = true;
    }
    var isFirefox3 = false;
    var isMozilla = window.netscape && !window.opera;
    if (isMozilla)
    {
        if (window.showModalDialog) { isFirefox3 = true; }
    }

    if (!window.ContensisControlsNamespace.Browser.IsFirefox3)
    {
        if (eventObject.preventCapture) eventObject.preventCapture();
        if (eventObject.preventBubble) eventObject.preventBubble();
    }
    return false;
}

function _CancelEventSafari() {
    return false;
}

function _Trim(str) {
    // skip leading and trailing whitespace
    // and return everything in between
    str = str.replace(/^\s*(.*)/, "$1");
    str = str.replace(/(.*)\s*$/, "$1");
    return str;
}

function _GetElementsByClassName(className, nodeElm, elmType) {
    var elementList = [];
    var elementsByClassName = [];
    if (elmType) elementList = nodeElm.getElementsByTagName(elmType);
    else elementList = document.all || document.getElementsByTagName("*");
    for (var i = 0, elm; elm = elementList[i]; i++)
    {
        if (this.HasClassName(elm, className))
        {
            elementsByClassName.push(elm);
        }
    }
    return elementsByClassName;
}
function _HasClassName(elm, className) {
    var re = RegExp("(^|\\s)" + className + "(\\s|$)");
    return re.test(elm.className);
}

function _SubtractDays(SourceDate, count) {
    return _AddSubtractFromDate(SourceDate, 0, count, true)
}
function _SubtractWeeks(SourceDate, count) {
    return _AddSubtractFromDate(SourceDate, 1, count, true)
}
function _AddSubtractFromDate(SourceDate, type, count, subtract) {
    // If the date is valid, proceed with the calculations

    // Strip out the month, day and year
    // JavaScript stores months as 0-11 as opposed to 1-12
    var EnteredMonth = SourceDate.getMonth();
    var EnteredDay = SourceDate.getDate();
    var EnteredYear = SourceDate.getYear();
    // Create a new date object with the entered month, day and year
    var EnteredDate = new Date(EnteredYear, EnteredMonth, EnteredDay, 0, 0, 0);
    // Determine the milliseconds in the timespan selected
    // Set the default (1 day)
    var MilliSecondsBase = 86400000
    // If the span selected is weeks, multiply the default by 7
    if (type == 1)
    {
        MilliSecondsBase *= 7;
    }
    // Multiply the millisecons by the period entered 
    MilliSecondsToAdd = MilliSecondsBase * count;
    // Create the new date using the correct operation
    if (!subtract)
    {
        var NewDateAsNumber = EnteredDate.getTime() + MilliSecondsToAdd;
    } else
    {
        var NewDateAsNumber = EnteredDate.getTime() - MilliSecondsToAdd;
    }
    // Create the new date object
    var NewDate = new Date(NewDateAsNumber);
    // Get the month, day and year values from the new date object
    // Set the month and day to two digits if they are less than 10      
    var NewMonth = NewDate.getMonth() + 1;
    if (NewMonth < 10)
    {
        NewMonth = "0" + NewMonth;
    }
    var NewDay = NewDate.getDate();
    if (NewDay < 10)
    {
        NewDay = "0" + NewDay;
    }
    var NewYear = NewDate.getFullYear();
    // Display the new date in the form
    var ReturnDate = new Date(NewYear, NewMonth - 1, NewDay, 0, 0, 0);
    return ReturnDate
}

function _ResetToStartOfDay(SourceDate) {

    // Display the new date in the form
    var ReturnDate = SourceDate.setHours(0, 0, 0, 0)
    return ReturnDate
}
function _ResetToEndOfDay(SourceDate) {

    // Display the new date in the form
    var ReturnDate = SourceDate.setHours(24, 59, 59, 0)
    return ReturnDate
}
function _GetDateForDotNet(dateobj) {
    // d/m/y
    var dateParts;
    if (typeof (dateobj) == 'string')
    {
        dateParts = dateobj.split('/');
    }
    if (typeof (dateobj) == 'object')
    {
        dateParts = [dateobj.getDate(), dateobj.getMonth() + 1, dateobj.getFullYear()];
    }
    var NewDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
    //var NewDate = new Date(dateobj);
    // Get the month, day and year values from the new date object
    // Set the month and day to two digits if they are less than 10
    var NewMonth = NewDate.getMonth() + 1;
    if (NewMonth < 10)
    {
        NewMonth = "0" + NewMonth;
    }
    var NewDay = NewDate.getDate();
    if (NewDay < 10)
    {
        NewDay = "0" + NewDay;
    }
    var NewYear = NewDate.getFullYear();
    var NewHour = NewDate.getHours();
    if (NewHour < 10)
    {
        NewHour = "0" + NewHour;
    }

    var NewMinutes = NewDate.getMinutes()
    if (NewMinutes < 10)
    {
        NewMinutes = "0" + NewMinutes;
    }
    var NewSeconds = NewDate.getSeconds()
    if (NewSeconds < 10)
    {
        NewSeconds = "0" + NewSeconds;
    }
    // Display the new date in the form
    var ReturnDate = NewYear + '-' + NewMonth + '-' + NewDay + ' ' + NewHour + ':' + NewMinutes + ':' + NewSeconds + '.000';
    return ReturnDate
}
if (typeof (window.ContensisControlsNamespace.Utilities) == "undefined" || typeof (window.ContensisControlsNamespace.Utilities) == null)
{
    window.ContensisControlsNamespace.Utilities = new Utilities();
}

function ContensisUser(userID, userName, isSystemAdministrator) {
    this.UserID = userID
    this.UserName = userName
    this.IsSystemAdministrator = isSystemAdministrator
}

//this is to store the key value pairs of the querystring    

// changed by dan so a url can be passed
function QueryStringObject(url) {
    if (url)
    {
        this.url = url;
    }
    else
    {
        this.url = window.location.href;
    }
    this.objects = new Array();
    this.add = _add;
    this.remove = _remove;
    this.item = _item;
    this.populateCollection = _populateCollection;
    this.setRawString = _setRawString;
    this.rawString = "";

    this.setRawString();
    this.populateCollection();

    // to add items to the array
    function _add(obj) {
        this.objects[this.objects.length] = obj;
    }
    //to remove items from the array
    function _remove(index) {
        this.objects.splice(index, 1);
    }
    //gets a reference to an item object
    function _item(searchKey) {
        searchKey = new String(searchKey);
        searchKey = searchKey.toLowerCase();
        for (i = 0; i < this.objects.length; i++)
        {
            //the current key in the coll
            var key = this.objects[i].key;
            key = new String(key);
            key = key.toLowerCase();

            if (key == searchKey)
            {
                return this.objects[i];
            }
        }
    }

    function _setRawString() {
        //Create regular expression object to retrieve the qs part
        // Used regex 'cause the search property on the location object includes the bookmark stuff
        var qsReg = new RegExp("[?][^#]*", "i");
        hRef = unescape(this.url); // window.location.href);
        var qsMatch = hRef.match(qsReg);
        //removes the question mark from the url 
        qsMatch = new String(qsMatch);
        qsMatch = qsMatch.substr(1, qsMatch.length - 1);
        this.rawString = qsMatch;
    }

    //takes a string and populates the array with the key/value pairs
    function _populateCollection(rawString) {
        this.rawString = new String(this.rawString);
        var rootArr = this.rawString.split("&");
        for (i = 0; i < rootArr.length; i++)
        {
            var tempArr = rootArr[i].split("=");
            if (tempArr.length == 2)
            {
                tempArr[0] = unescape(tempArr[0]);
                tempArr[1] = unescape(tempArr[1]);

                this.add(new qsValue(tempArr[0], tempArr[1]));
            }
        }
    }

    function qsValue(key, value) {
        this.key = key;
        this.value = value;
    }
}

function Utilities_SaveCurrentEditor() {
    if (top.window.ContensisControlsNamespace.CurrentEditor)
    {
        if (top.window.ContensisControlsNamespace.CurrentEditor.Toolbar)
        {
            top.window.ContensisControlsNamespace.CurrentEditor.Toolbar.ToolButtons[0].ToolClick();
        }
    }
}


function _Utilities_CreateDelegate(instance, method) {
    return function() {
        return method.apply(instance, arguments);
    }
}

function _Utilities_AddHandler(element, eventName, func, context, useCapture, param) {
    var result = false;
    if (!element._events)
    {
        element._events = [];
    }
    var delegate = this.CreateDelegate(context, func);
    var handler;
    if (element.addEventListener)
    {
        handler = function(e) { return delegate.call(element, e, element, param) };
        element.addEventListener(eventName, handler, useCapture);
        result = true;
    }
    else
    {
        if (element.attachEvent)
        {
            handler = function(e) {
                if (!e)
                {
                    try { e = window.event; }
                    catch (ex) { }
                }
                return delegate.call(element, e, element, param);
            };
            element.attachEvent('on' + eventName, handler);
        }
    }
    element._events[element._events.length] = { eventName: eventName, delegate: delegate, handler: handler };
    return delegate;
}

function _Utilities_RemoveHandler(element, eventName, delegate) {
    var handler = null;
    if ((typeof (element._events) !== 'object') || (element._events == null))
    {
        return false;
    }
    var cache = element._events[eventName];
    if (!(cache instanceof Array))
    {
        return false;
    }
    if (delegate)
    {
        for (var i = 0; i < cache.length; i++)
        {
            if (cache[i].delegate === delegate)
            {
                handler = cache[i].handler;
                break;
            }
        }
        if (typeof (handler) !== 'function') { return false; }
        if (element.removeEventListener)
        {
            element.removeEventListener(eventName, handler, false);
        }
        else
        {
            if (element.detachEvent)
            {
                element.detachEvent('on' + eventName, handler);
            }
        }
        cache.splice(i, 1);
    }
    else
    {
        var i = 0;
        var length = cache.length;
        while (i < length)
        {
            if (cache[i].eventName == eventName)
            {
                handler = cache[i].handler;
                if (typeof (handler) == 'function')
                {
                    if (element.removeEventListener)
                    {
                        element.removeEventListener(eventName, handler, false);
                    }
                    else
                    {
                        if (element.detachEvent)
                        {
                            element.detachEvent('on' + eventName, handler);
                        }
                    }
                }
                cache.splice(i, 1);
                length -= 1;
            }
            else { i += 1; }
        }
    }
}

function _Utilities_CleanUp() {
    CollectGarbage();
}

function _Utilities_RegisterGlobalObject(obj) {
    if (typeof (this.GlobalObjects) == 'undefined')
    {
        this.GlobalObjects = new Array();
    }
    var result = this.GlobalObjects.length;
    this.GlobalObjects[result] = obj;
    return result;
}

function _Utilities_GetGlobalObject(index) {
    if (typeof (this.GlobalObjects) == 'undefined')
    {
        return null;
    }
    if (this.GlobalObjects.length > index)
    {
        return this.GlobalObjects[index];
    }
    return null;
}

function _Utilities_RegisterExpandoProperty(element, propertyName) {
    if (typeof (this.Expando) == 'undefined')
    {
        this.Expando = new Array();
    }
    this.Expando[this.Expando.length] = { element: element, propertyName: propertyName };
}

function _Utilities_ClearExpandoProperties() {
    var s = 'Expando: ';
    if (typeof (this.Expando) != 'undefined')
    {
        s += this.Expando.length;
        for (var i = 0; i < this.Expando.length; i++)
        {
            var obj = this.Expando[i];
            obj.element[obj.propertyName] = null;
            obj.element = null;
            //delete obj.element[obj.propertyName];
        }
    }
    s += '    Events: ';
    if (typeof (this.Events) != 'undefined')
    {
        s += this.Events.length;
        for (var i = 0; i < this.Events.length; i++)
        {
            var obj = this.Events[i];
            this.RemoveEvent(obj.element, obj.eventType, obj.lamdaFunction, obj.useCapture);
            obj.element = null;
        }
    }
    //alert(s);
    this.Expando = new Array();
    this.Events = new Array();
    if (typeof (CollectGarbage) != 'undefined')
    {
        CollectGarbage();
    }
}

function _Utilities_RegisterElements() {
    /*
    var els = document.getElementsByTagName('*');
    var count = 0;
    for (var i=0; i<els.length; i++)
    {
    var el = els[i];
    for (prop in el)
    {
    count += 1;
    }
    }
    alert(count);*/
}

function _Utilities_ClearElements() {
    /*
    var els = document.getElementsByTagName('*');
    var count = 0;
    for (var i=0; i<els.length; i++)
    {
    var el = els[i];
    for (prop in el)
    {
    count += 1;
    }
    }
    alert(count);*/
}

function _Utilities_CloseWindow(ReturnValue) {
    if (ContensisControlsNamespace.Browser.IsSafari) {
        if (ReturnValue) { window.top.returnValue = ReturnValue; }
        window.top.close();
        return;
    }
    if (ContensisControlsNamespace.Browser.IsFirefox3)
    {
        if (ReturnValue) { window.top.returnValue = ReturnValue; }
        window.top.close();
        return;
    }
    if (ContensisControlsNamespace.Browser.IsChrome) {
        if (ReturnValue) { window.top.returnValue = ReturnValue; }
        window.top.close();
        return;
    }    
    if (ContensisControlsNamespace.Browser.IsIE)
    {
        if (ReturnValue) { window.returnValue = ReturnValue; }
        window.close();
        return;
    }
}

function _Utilities_Destroy() {
    document.getElementById("_ctl6").src = 'javascript:false';
    setTimeout(function() { CloseFunc(); }, 1);
}

function CloseFunc() {
    //document.getElementById("_ctl6").contentWindow.ContensisControlsNamespace.Utilities
    window.close();
}

function _Utilities_BuildListItems(s) {
    var result = new Array();
    var sXML = s.replace(/{/ig, '<');
    sXML = sXML.replace(/}/ig, '>');
    var doc = window.ContensisControlsNamespace.Global.Helpers.parseXml(sXML);
    var items = doc.documentElement;
    if (items)
    {
        for (var i = 0; i < items.childNodes.length; i++)
        {
            var item = items.childNodes[i];
            if (item.childNodes.length == 3)
            {
                result[i] = {};
                result[i].Name = item.childNodes[0].text;
                result[i].Value = item.childNodes[1].text;
                result[i].Checked = (item.childNodes[2].text.toUpperCase() == 'TRUE');
            }
        }
    }
    return result;
}

function Utilities_EscapeStringForRegEx(text) {
    if (!text) { return ''; }
    var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
    var re = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
    return text.replace(re, '\\$1');
}

function Utilities_DoConfirm(ConfirmText, EnableLoader) {
    var ReturnVal = confirm(ConfirmText)
    if (ReturnVal)
    {
        if (EnableLoader)
        {
            this.ShowFullScreenOverlay();
        }
    }
    return ReturnVal;
}
