﻿/*
 *  Mangrove.js
 *  Copyright © 2007 Mangrove Software Inc. 
 *
 *  Author:     Zac McCormick
 *  Created:    Jan 24, 2007
 */
 
 
if (typeof(Mangrove) == 'undefined') { Mangrove = {} };

//basic browser detection flags
MSIE = (navigator.userAgent.indexOf("MSIE") > -1);
MSIEVER = MSIE && parseFloat(navigator.appVersion.split('MSIE')[1]);
MSIE6 = MSIE && Math.floor(MSIEVER) == 6.0;
MSIE7 = MSIE && Math.floor(MSIEVER) == 7.0;
MSIE8 = MSIE && Math.floor(MSIEVER) == 8.0;
FIREFOX = (navigator.userAgent.toLowerCase().indexOf("firefox") > -1);
SAFARI  = (navigator.userAgent.toLowerCase().indexOf("safari") > -1);
CHROME  = (navigator.userAgent.toLowerCase().indexOf("chrome") > -1);


Mangrove._AspNetPrefix = 'ctl00_';

//wrappers to abstract the browser differences with event handlers
$addEvent = function(obj, type, func) {
    if (obj.attachEvent) // IE
        obj.attachEvent('on' + type, func);
    else if (obj.addEventListener) // W3C DOM Compliant
        obj.addEventListener(type, func, false);
    else //ewww
        obj['on' + type] = func;
}

$removeEvent = function(obj, type, func) {
    if (obj.detachEvent)
        obj.detachEvent('on' + type, func);
    else if (obj.removeEventListener)
        obj.removeEventListener(type, func, false);
    else //ewww
        obj['on' + type] = null;
}


// fix for css background image flicker when using javascript to alter positioning
if (MSIE6) {
    try {
        document.execCommand('BackgroundImageCache', false, true);
    } catch(err) {}
}


//global collection of load events
Mangrove.WindowLoadEvents = [];


//global function to add a load event for a page
if (typeof(window.$addLoadEvent) == 'undefined') {
    window.$addLoadEvent = function(func) {
        Mangrove.WindowLoadEvents.push(func);
    }
}


//internal method that invokes all of the load handlers
Mangrove._invokeLoadEvents = function() {
    for (var i = 0; i < Mangrove.WindowLoadEvents.length; ++i)
        Mangrove.WindowLoadEvents[i]();
}


//hook the global window.load event to call our internal dispatcher so we can easily have multiple handlers
$addEvent(window, 'load', Mangrove._invokeLoadEvents);


if (top.frames.topFrame) {
    //every page will call this handler first on PODs screens
    $addLoadEvent(function() {

        //sync the cookie with the server, find the function in one of the window contexts, this needs to be fixed.
        if (top && typeof(top.topFrame) != 'undefined' && typeof(top.topFrame.resetSessionTimeout) == 'function') {
            top.topFrame.resetSessionTimeout();
        } else if (top && typeof(top.resetSessionTimeout) == 'function') {
            top.resetSessionTimeout();
        } else if (typeof(window.resetSessionTimeout) == 'function') {
            window.resetSessionTimeout();
        }

        //if there is a pageError element on the page, alert it's value
        var pageError = document.getElementById('pageError');
        if (pageError) {
            setTimeout(function(){alert(this.msg)}.bind({msg:pageError.value}), 100);
        }
        
        //if there is a initMessage element on the page, alert it's value
        var initMessage = document.getElementById('initMessage');
        if (initMessage) {
            setTimeout(function(){alert(this.msg)}.bind({msg:initMessage.value}), 100);
        }
        
        //fix the <fieldset> elements on PODs screens and align their frame labels (this is specifically to make the pages work with PODS).
        _execGroupboxFix(true);
        
        //assign any Active Default's for this page
        for (var i = 0; i < DefaultValueElements.length; ++i) {
            var textbox = document.getElementById(DefaultValueElements[i]);

            if (textbox && !textbox.disabled && textbox.value.trim().length == 0) {
                var def = textbox.defaultvalue;
                if (def && def.length > 0) {
                    switch (def) {
                        case '{today}':
                            var dt = new Date();
                            textbox.value = formatDate(dt);
                           
                            break;
                            
                        default:
                            textbox.value = def;
                    }
                }
            }   
        }
        
        
        //here is where we set the navigation for the screen being loaded.
        //ideally this code would be somewhere in the codepath for pages
        //included in the hr2oScreen frame and would make this check unneccesary.
        var changeNav = document.getElementById('changeNav');
        
        var url = window.location.toString().toLowerCase();
        
        
        var noNavigation = [
            'appnav.aspx',
            'eenav.aspx',
            'topframev5.aspx',
            'start.aspx',
            'sidebar.aspx',
            'roleselector.aspx',
            'buildmenus.aspx'
        ];
        
        var noNav = false;
        
        for (var j = 0; j < noNavigation.length; ++j) {
            if (url.indexOf(noNavigation[j]) > -1) {
                noNav = true;
                break;
            }  
        }
        
        if (changeNav && !noNav)
            ChangeNav(changeNav.value);


        //HACK to make the Telerik RAD Grid to work properly within the app.
        removeRadGridRightMargins(document);
    });
}



//global wrapper for document.getElementById
if (typeof($) == 'undefined') {
    $ = function(something) {
        if (typeof(something) != 'string')
            return something;
            
	    return document.getElementById(something);
    }
}

//global wrapper for document.getElementById
//if (typeof($$) == 'undefined') {
    $$ = function(something) {
        if (typeof(something) != 'string')
            return something;
            
	    return document.getElementById(something);
    }
//}

//global wrapper to get an element on an ASPX page from its server ID
if (typeof($g) == 'undefined') {
    $g = function(something) {
        return $(Mangrove._AspNetPrefix + something);
    }
}
 
//global wrapper to get an element on an PODs page from its server ID
if (typeof($p) == 'undefined') {
    $p = function(something) {
        return $(Mangrove._AspNetPrefix + 'ScreenPH_' + something);
    }
}


/*
returns an array of elements that match the given class name

usage:
 var nodes = $getElementsByClassName(someElement, 'div', 'the-class-name');
   OR
 var nodes = $getElementsByClassName('the-class-name');
 
*/

if (typeof($getElementsByClassName) == 'undefined') {
    $getElementsByClassName = function(root, tagName, className){

        var classElements = new Array();
        if (root == null)
            root = document;
        if (tagName == null)
            tagName = '*';
        var els = root.getElementsByTagName(tagName);
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
        for (i = 0, j = 0; i < elsLen; i++) {
            if (pattern.test(els[i].className)) {
                classElements[j] = els[i];
                j++;
            }
        }
        return classElements;
    
    
        /*
        if (arguments.length == 1) {
            className = root;
            root = document;
            tagName = '*';
        }
        
        tagName = tagName || '*';
        
	    var elements = (tagName == '*' && root.all)? root.all : root.getElementsByTagName(tagName);
	    var matchedElements = [];
    	
	    className = className.replace(/\-/g, '\\-');
    	
	    var element;
	    var regExp = new RegExp('(^|\\s)' + className + '(\\s|$)');
    	
	    for (var i = 0; i< elements.length; ++i) {
		    element = elements[i];
    				
		    if (regExp.test(element.className)){
			    matchedElements.push(element);
		    }	
	    }
    	
	    return matchedElements;
	    */
    }
}


//add a class to an element
if (typeof($addClassName) == 'undefined') {
    $addClassName = function(element, className){
	    var currentClass = element.className;
    	
	    if (!(new RegExp(className, 'i')).test(currentClass)) {
		    element.className = currentClass + (currentClass.length > 0 ? ' ' : '') + className;
	    }
    }
}


//remove a class from an element
if (typeof($removeClassName) == 'undefined') {
    $removeClassName = function(element, className){
	    var classToRemoveRegExp = new RegExp((className + '\s?'), 'i');
	    element.className = element.className.replace(className, '').replace(/^\s?|\s?$/g, '');
    }
}



function removeRadGridRightMargins(doc) {
    doc = doc || document;
    //hack the r.a.d. grid to remove the 17px right margin on the header
    var tables = doc.getElementsByTagName('table');
    
    for (var i = 0; i < tables.length; ++i) {
        var __table = tables[i];
        if (__table.className.indexOf('MasterTable_WebBlue') > -1) {
            if (__table.parentNode && __table.parentNode.id.indexOf('_GridHeader') > -1) {
                //firefox timing bug
                setTimeout(function(){
                    this.parentNode.style.marginRight = '0px';
                }.bind(__table), (window.attachEvent ? 1 : 500));
            }
        }
    }
}


function formatDate(dt) {
    return (dt.getMonth() + 1) + '/' + dt.getDate() + '/' + dt.getFullYear();
}



function preloadImages(images) {
    var imgArray = [];
    for (var i = 0; i < images.length; ++i) {
        var n = new Image();
        n.src = images[i];
        imgArray[imgArray.length - 1] = n;
    }
    return imgArray;
}





Cookie = {
  supports: function() {
    try {
      document.cookie = 'cookiez=true';
      
      if(Cookie.get('cookiez') == 'true') {
        Cookie.remove('cookiez');
        return true;
      } else {
        return false;
      }
    } catch(ex) { return false; }
  },
  
  set: function(name, value, expires, path, domain, secure) {
    if( !Cookie.supports() )
      return false;
      
    if (typeof(expires) == 'number')
        expires = addDays(new Date(), expires);
    
    document.cookie = name + '=' + escape(value) +
        ((expires) ? '; expires=' + expires.toGMTString() : '') +
        ((path)    ? '; path='    + path : '') +
        ((domain)  ? '; domain='  + domain : '') +
        ((secure)  ? '; secure' : '');

    return true;
  },
  
  get: function(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    
    if (end == -1)
        end = dc.length;
        
    return unescape(dc.substring(begin + prefix.length, end));
  },
  
  remove: function(name, path, domain) {
    if (Cookie.get(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
  }
}


function addDays(dt, days) {
    return new Date(dt.getTime() + days*24*60*60*1000);
}



$pod = function(id) {
    return document.getElementById(mangle(id));
}

$comboValue = function(cbo) {
    if (typeof(cbo) == 'string')
        cbo = $pod(cbo) || $(cbo);
    
    if (cbo.selectedIndex > -1)
        return cbo.options[cbo.selectedIndex].value;
    else return null;
}

$comboText = function(cbo) {
    if (typeof(cbo) == 'string')
        cbo = $pod(cbo) || $(cbo);
    
    if (cbo.selectedIndex > -1)
        return cbo.options[cbo.selectedIndex].text;
    else return null;
}


function setComboItem(combo, item) {
    if (typeof(combo) == 'string')
        combo = $(combo);
        
    if (combo) {
        //exact match
        for (var i = 0; i < combo.options.length; ++i) {
            if (combo.options[i].value == String(item) || combo.options[i].text == String(item)) {
                combo.selectedIndex = i;
                return;
            }
        }
        
        //case sensitive match
        for (var i = 0; i < combo.options.length; ++i) {
            var rx = new RegExp(String(item));
            if (combo.options[i].value.match(rx) || combo.options[i].text.match(rx)) {
                combo.selectedIndex = i;
                return;
            }
        }
        
        //case insensitive match
        for (var i = 0; i < combo.options.length; ++i) {
            var rx = new RegExp(String(item), "i");
            if (combo.options[i].value.match(rx) || combo.options[i].text.match(rx)) {
                combo.selectedIndex = i;
                return;
            }
        }
    }
}


// returns the server-side ID of the screen field. eg: 'ctl00_ScreenPH_cmdButtons_1' --> 'cmdButtons_1'
function unMangle(id) {
    var rx = new RegExp(Mangrove._AspNetPrefix + 'ScreenPH_(.+)');
    
    if (id.match(rx)) {
        return RegExp.$1;
    }
    return '';
}



// returns the mangled name given the server-side ID. eg: 'cmdButtons_1' --> 'ctl00_ScreenPH_cmdButtons_1'
function mangle(id) {
    return Mangrove._AspNetPrefix + (id.substring(0, 2) == 'vs' ? '' : 'ScreenPH_') + id;
}

// returns the control index based on a non-mangled field ID. eg: 'cmdButtons_1' -> '1'
function getControlIndex(id) {
    var rx = new RegExp('[^_]+_([0-9]{1,4})');
    
    if (id.match(rx)) 
        return RegExp.$1;
    
    return '';
}


function isEditMode() {
    return /insert|update/i.test(document.getElementById(mangle('vsEditMode')).value);
}

function isScreenObject() {
    return getScreenId() != '-1';
}

function getScreenId() {
    if (window.location.toString().match(/\/(val|det|tab|wiz)([0-9]{1,5})(\.aspx\?{0,1})/gim)) {
        return RegExp.$2;
    } else {
        return '-1';
    }
}


if (typeof(stopEvent) == 'undefined') {
    function stopEvent(event) {
        if (window.attachEvent) {
            event.returnValue = false;
            event.cancelBubble = true;
        } else {
            event.preventDefault();
            event.stopPropagation();
        }
        
        if (window.attachEvent)
            event.keyCode = 0;
        
        return false;
    }
}




var StringExtensions = {
    left: function(text, n) {
        if (n < 1)
            return '';
        else if (n > String(text).length)
            return text;
        else
            return String(text).substring(0, n);
    },
    
    right: function(text, n) {
        if (n < 1) {
            return '';
        }
        if (n > String(text).length) {
            return text;
        }
        else {
            var len = String(text).length;
            return String(text).substring(len, len - n);
        }
    },
    
    ltrim: function(text) {
        return (text || '').replace(/^\s+/, '');
    },
    
    rtrim: function(text) {
        return (text || '').replace(/\s+$/, '');
    },
    
    trim: function(text) {
        return (text || '').replace(/^\s+|\s+$/g, '');
    }   
}


if (window.String.prototype) {
    String.prototype.left = function(n) {
        return StringExtensions.left(this, n);
    }
    
    String.prototype.right = function(n) {
        return StringExtensions.right(this, n);
    }
    
    String.prototype.rtrim = function() {
        return StringExtensions.rtrim(this);
    }
    
    String.prototype.ltrim = function() {
        return StringExtensions.ltrim(this);
    }
    
    String.prototype.trim = function() {
        return StringExtensions.trim(this);
    }
}




//a routine to return a function object bound to an object instance,
//used to call a function and set the 'this' context for the function
if (typeof(Function.prototype.bind) == 'undefined') {
    Function.prototype.bind = function(object) {
        var __method = this;
        return function() {
            __method.apply(object, arguments);
        };
    };
}




//disables the selection of text of an element
function setNoSelect(element) {
    if (window.attachEvent)
        element.unselectable = 'on'; // MSIE
    else if (navigator.product == 'Gecko')
        element.style.MozUserSelect = 'none'; // Firefox/Mozilla
    else
        element.style.KhtmlUserSelect = 'none'; // KHTML/WebKit
}




//opens the attachment window for the screen object
function showAttachmentWindow(caption) {
    var id, obj, screenId;
    
    caption = caption || 'Attachments';
    
    obj = $g('vsEmployeeId');
    
    if (obj)
	    id = obj.value;
	else
	    id = $g('vsRowId').value;
	    
	screenId = getScreenId();
	
	top.showOverlay('../SysForms/AttachmentManager.aspx?m=&' + (isEditMode() ? 'e=&' : '') + 'oid=' + screenId + '&rid=' + (id || '-1'));

    return false;
}


//generic error handler for PODs cmbButton's
function cmdButtons_clickError(buttonWithError, ex) {
    alert('There was an error in the button click handler!\n\n' + (ex.description || ex.message));
}

//opens a PODs Detail Screen (context MUST be RowId for now)
function openDetailRecord(objectId, width, height, context, isCode) {
    top.showOverlay('../Screens/det' + objectId + '.aspx?m=&' + (isCode ? 'Code=' : 'RowId=') + (context || '-1'), width || 400, height || 300);
}


//opens a PODs Detail Screen filtered
function openDetailRecordWithFilter(objectId, filterColumn, filterValue, filterType, callback) {
    if (typeof(filterType) == 'undefined')
        filterType = 'LIKE';
        
    top.showOverlay('../Screens/det' + objectId + '.aspx?m=&fc=' + encodeURIComponent(filterColumn) + '&fv=' + encodeURIComponent(filterValue) + '&ft=' + encodeURIComponent(filterType), null, null, callback);
}


//opens a PODs Validation Screen
function openValRecord(objectId, width, height, context, isCode) {
    top.showOverlay('../Screens/val' + objectId + '.aspx?m=&' + (isCode ? 'Code=' : 'RowId=') + (context || '-1'), width || 400, height || 300);
}



//generic inclusion function to find the navigation frame and call ChangeNav
function ChangeNav(screen) {
    var frame = top.frames['EEFrame'];
    
    if (frame && typeof(frame.ChangeNav) == 'function') {
        frame.ChangeNav(screen);
    }
}


//set element opacity
function $setOpacity(element, opacity) {
    if (typeof(element.style.filter) != 'undefined') { // MSIE
        if (parseInt(opacity) == 1) {
            element.style.filter = '';
        }
        else 
            element.style.filter = 'alpha(opacity=' + parseInt(opacity*100) + ')';
    } else if (navigator.product == 'Gecko') { // Mozilla/Firefox
        element.style.MozOpacity = opacity;
    } else { // KHTML/Safari
        element.style.opacity = opacity;
    }
}


//shows the calendar for the given textbox
function showCalendar(event, textbox, mangled) {
    if (typeof(Mangrove._AspNetPrefix) == 'undefined')
        Mangrove._AspNetPrefix = 'ctl00_';
        
    if (typeof(mangled) == 'undefined')
        mangled = true;
        
    var tb = document.getElementById(mangled ? (Mangrove._AspNetPrefix + 'ScreenPH_' + textbox) : textbox);
    
    if (tb.readOnly || tb.disabled) {
        if (tb.id.match(/txtFields/))
            alert('You must be in edit mode in order to modify the date!');
        else
            alert('The date field is not editable!');
        return;
    }
    
    var onCalendarClose = function(rs) {
        if (rs != null) {
            tb.value = rs;
            tb.focus();
        }
    }
    
    var x, y;
    
    x = y = 0;
    
    if (typeof(event.clientX) != 'undefined') {
        x = event.clientX + document.body.scrollLeft;
        y = event.clientY + document.body.scrollTop;
    } else {
        x = e.pageX;
        y = e.pageY;
    }
    
    if (top == window) {
        x += getScrollLeft();
        y += getScrollTop();
    }
    
    
    top.showCalendarFrame(tb.value, x, y, onCalendarClose);
}






//shows the calendar for the given textbox
function showCalendarFiltered(event, textbox, mangled, employeeID, filterType) {
    if (typeof (Mangrove._AspNetPrefix) == 'undefined')
        Mangrove._AspNetPrefix = 'ctl00_';

    if (typeof (mangled) == 'undefined')
        mangled = true;

    var tb = document.getElementById(mangled ? (Mangrove._AspNetPrefix + 'ScreenPH_' + textbox) : textbox);

    if (tb.readOnly || tb.disabled) {
        if (tb.id.match(/txtFields/))
            alert('You must be in edit mode in order to modify the date!');
        else
            alert('The date field is not editable!');
        return;
    }

    var onCalendarClose = function(rs) {
        if (rs != null) {
            tb.value = rs;
            tb.focus();
        }
    }

    var x, y;

    x = y = 0;

    if (typeof (event.clientX) != 'undefined') {
        x = event.clientX + document.body.scrollLeft;
        y = event.clientY + document.body.scrollTop;
    } else {
        x = e.pageX;
        y = e.pageY;
    }

    if (top == window) {
        x += getScrollLeft();
        y += getScrollTop();
    }


    top.showCalendarFrameFiltered(tb.value, x, y, onCalendarClose, employeeID, filterType);
}




if (typeof(isInteger) == 'undefined') {
    isInteger = function(value) {
        var rs = false;
        try {
            var num = parseInt(value);
            if (isNaN(num))
                rs = false;
            else rs = true;
        } catch (ex) {}
        return rs;
    }
}

if (typeof(isNumeric) == 'undefined') {
    isNumeric = function(value) {
        var rs = false;
        try {
            var num = parseFloat(value);
            if (isNaN(num))
                rs = false;
            else rs = true;
        } catch (ex) {}
        return rs;
    }
}

if (typeof(isDate) == 'undefined') {
    isDate = function(value) {
        var rs = false;
        try {
            var d = Date.parse(value);
            if (isNaN(d))
                rs = false; 
            else rs = true;
        } catch (ex) {}
        return rs;
    }
}



if (typeof(Ajax) == 'undefined') {
    Ajax = {};

    Ajax.get = function(url, callback) {
        var req = null;
        
        if (window.XMLHttpRequest && !window.ActiveXObject) {
    	    try {
			    req = new XMLHttpRequest();
            } catch (e) {
			    req = false;
            }
        } else if (window.ActiveXObject) {
       	    try {
        	    req = new ActiveXObject('Msxml2.XMLHTTP');
      	    } catch (e) {
        	    try {
          		    req = new ActiveXObject('Microsoft.XMLHTTP');
        	    } catch (e) {
          		    req = false;
        	    }
		    }
        }
        
        
	    if (req) {
	        var __req = req;
    	    
		    req.onreadystatechange = function() {
                if (__req.readyState == 4) {
                    if (__req.status == 200) {
                        callback(__req);
                    } else {
                        alert('There was a problem retrieving the data:\n' + __req.statusText + '\n\n' + __req.responseText);
                    }
                }  
		    }
    		
		    req.open('GET', url, true);
    		
		    req.setRequestHeader('X-Requested-With', 'Mangrove.Ajax');
    		
		    req.send('');
	    }
    }


    Ajax.post = function(url, postData, callback) {
        var req = null;
        
        if (window.XMLHttpRequest && !window.ActiveXObject) {
    	    try {
			    req = new XMLHttpRequest();
            } catch(e) {
			    req = false;
            }
        } else if (window.ActiveXObject) {
       	    try {
        	    req = new ActiveXObject('Msxml2.XMLHTTP');
      	    } catch (e) {
        	    try {
          		    req = new ActiveXObject('Microsoft.XMLHTTP');
        	    } catch (e) {
          		    req = false;
        	    }
		    }
        }
        
	    if (req) {
	        var __req = req;
    	    
		    req.onreadystatechange = function() {
                if (__req.readyState == 4) {
                    if (__req.status == 200) {
                        callback(__req);
                    } else {
                        alert('There was a problem retrieving the data:\n' + __req.statusText + '\n\n' + __req.responseText);
                    }
                }  
		    }
    		
		    req.open('POST', url, true);
    		
		    req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            req.setRequestHeader('Content-length', postData.length);
            req.setRequestHeader('X-Requested-With', 'Mangrove.Ajax');
            //req.setRequestHeader('Connection', 'close');
            
		    req.send(postData);
	    }
    }

    Ajax.evalResponse = function(req) {
        var rs;
        try {
            rs = eval('(' + req.responseText + ')');
        } catch (ex) {
            alert('There was an error processing the response.\n' + ex.message + '\n' + req.responseText);
            return;
        }
        return rs;
    }
}

groupboxRoot = null;

groupboxFixes = [];

function fixGroupbox(frame, title, tabNum) {
    groupboxFixes.push({'frame':frame, 'title':title, 'tabNum':tabNum});
}

function _execGroupboxFix(again) {
    for (var i = 0; i < groupboxFixes.length; ++i) {
        _fixGroupbox(groupboxFixes[i].frame, groupboxFixes[i].title, groupboxFixes[i].tabNum);
    }

    if (again) {
        setTimeout(function() {_execGroupboxFix(false);}, 300);
    }
}

function _fixGroupbox(frame, title, tabNum) {
    frame = document.getElementById(frame);
    
    tabNum = Math.max(tabNum - 1, 0);
    
    if (groupboxRoot == null) {
        groupboxRoot = document.getElementById('ctl00_ScreenPH_tabFrame_' + tabNum);
    }
    
    var label = document.getElementById(frame.id + '_title');
    
    if (title.length > 0 && !label) {
        label = document.createElement('span');
        groupboxRoot.appendChild(label);
        label.appendChild(document.createTextNode(title));
        label.id = frame.id + '_title';
        label.style.fontSize = '11px';
        label.style.fontFamily = 'Arial Narrow, "MS Sans Serif", Arial, Verdana, sans-serif';
        label.style.whiteSpace = 'nowrap';
        label.style.backgroundColor = '#fff';
        label.style.padding = '0px 1px';
        label.style.zIndex = 1000;
        label.style.position = 'absolute';
        label.style.color = 'navy';
    }
    
    if (label) {
        label.style.top = (frame.offsetTop - 6) + 'px';
        label.style.left = (frame.offsetLeft + 5) + 'px';
    }
}

function fixCheckboxLabel(checkbox) {
    checkbox = document.getElementById(checkbox);
    
    if (checkbox && checkbox.disabled) {
        if (checkbox.parentNode.tagName.toLowerCase() == 'span')
            checkbox.parentNode.disabled = false;
    }
}

function fixRadioLabel(radio) {
    radio = document.getElementById(radio);
    
    if (radio && radio.disabled) {
        if (radio.parentNode.tagName.toLowerCase() == 'span')
            radio.parentNode.disabled = false;
    }
}


DefaultValueElements = [];

function setDefaultValueEvents(id) {
    var textbox = document.getElementById(id);

    DefaultValueElements.push(id);
    
    if (textbox) {
        //$addEvent(textbox, 'focus', focusDefaultValue);
        //$addEvent(textbox, 'blur', blurDefaultValue);
    }
}

function focusDefaultValue(event) {
    event = event || window.event;
    
    var src = event.srcElement || event.target;
    
    if (src && typeof(src.defaultValue) == 'string') {
        if (src.value == '') {
            src.value = src.defaultValue;
        }
    }
}

function blurDefaultValue(event) {
    event = event || window.event;
}




function $focusDocument(doc) {
    doc = doc || window.document;
    setTimeout(function() {
        if (window.attachEvent)
            doc.body.focus();
        else
            doc.forms[0].elements[0].focus();
    }, 10);
}




function setScreenObjectOverlaySize(w) {
    var st = w.document.getElementById('screen-table');
    
    if (st) {
        w.document.body.style.width = (st.offsetWidth) + 'px';
        w.document.body.style.height = (st.offsetHeight + 5) + 'px';
    }
}









if (typeof(window.HTMLElement) != 'undefined' && !window.HTMLElement.prototype.insertAdjacentElement) {
	HTMLElement.prototype.insertAdjacentElement = function(where, node) {
		switch (where) {
		case 'beforeBegin':
			this.parentNode.insertBefore(node, this)
			break;
		case 'afterBegin':
			this.insertBefore(node, this.firstChild);
			break;
		case 'beforeEnd':
			this.appendChild(node);
			break;
		case 'afterEnd':
			if (this.nextSibling) {
			    this.parentNode.insertBefore(node, this.nextSibling);
			} else {
			    this.parentNode.appendChild(node);
			}
			break;
		}
	}
    
	HTMLElement.prototype.insertAdjacentHTML = function(where, html) {
		var r = this.ownerDocument.createRange();
		
		r.setStartBefore(this);
		
		var parsedHTML = r.createContextualFragment(html);
		
		this.insertAdjacentElement(where, parsedHTML)
	}


	HTMLElement.prototype.insertAdjacentText = function(where, text) {
		var textNode = document.createTextNode(text)
		this.insertAdjacentElement(where, textNode)
	}
}



function refreshPage() {
    var url = window.location.toString();
    
    url = url.replace(/now\=[0-9]+\&?/gi, '');

    if (url.indexOf('?') < 0)
        url = url + '?';
    
    if (url.substr(url.length - 1, 1) == '&')
        window.location = url + 'now=' + (new Date()).getTime().toString();
    else
        window.location = url + '&now=' + (new Date()).getTime().toString();
}



function alpha_mouseover(event, element, noHover) {
    $removeClassName(element, 'alpha-out');
    $addClassName(element, 'alpha-over');
    
    if (noHover != true && element.tagName.toLowerCase() == 'td') {
        element.style.backgroundColor = '#f1f1f1';
        element.style.border = '1px outset #9a9a9a';
    }
}

function alpha_mouseout(event, element) {
    $removeClassName(element, 'alpha-over');
    $addClassName(element, 'alpha-out'); 
       
    if (element.tagName.toLowerCase() == 'td') {
        element.style.backgroundColor = 'transparent';
        element.style.border = '1px solid #fff';
    }
}





function runCrystalReport(objectID) {
    top.showOverlay('../SysForms/ReportFilter.aspx?m=&r=' + objectID);
}


function $screen(url) {
    top.frames.hr2oScreen.location = url;
}
















SecurePage = {};



//global reference for help window
SecurePage.HelpWindow = null;

//help event handler
SecurePage.onHelp = function(helpCode) {
    var helpID = $('HelpContextID') ? $('HelpContextID').value : '-1';
    
    if (helpID.length < 1)
        helpID = '-1';
        
    //create a function that wraps the window.open and assignment of the global window context variable (SecurePage.HelpWindow)
    var createHelpWindow = function() {
        SecurePage.HelpWindow = window.open('../SysForms/Help.aspx?id=' + helpID, 'SecurePageHelpWindow', 'location=0, resizable=1, scrollbars=1');
    }
    
    //if the window exists, try to focus it, if that fails, invoke our create function. If the window doesn't exist, create it!
    if (typeof(SecurePage.HelpWindow) != 'undefined' && SecurePage.HelpWindow != null) {
        try {
            SecurePage.HelpWindow.focus();
        } catch (ex) {
            createHelpWindow();
        }
    } else {
        createHelpWindow();
    }
    
    return false;
}


//setup browser function reference
window.onhelp = SecurePage.onHelp;


//get query string variable
if (typeof($q) == 'undefined') {
    $q = function(q) {
        var query = window.location.search.substring(1);
        
        var queryParts = query.split('&');
        
        for (var i = 0; i < queryParts.length; ++i) {
            var pair = queryParts[i].split('=');
            
            if (pair[0] == q)
                return pair[1];
        }
        
        return null;
    }
}



//constants for the modal dialogs
OK     = 1;
CANCEL = 2;
YES    = 4;
NO     = 8;


/*
Shows a simple modal dialog with a question or information, and return the user's selection to a callback function

usage:

var dialogTitle    = 'This is the title';
var dialogContent  = 'Main text content, this can be arbitrary <strong>HTML</strong>.';
var dialogType     = YES | NO | CANCEL;
var dialogCallback = function(rs) {
    if (rs.yes) {
        alert('You pressed yes.');
    } else if (rs.no) {
        alert('You pressed no.');
    } else if (rs.cancel) {
        alert('You pressed cancel.');
    } else if (rs.ok) {
        alert('You pressed ok.');
    }
}

Mangrove.showDialog(dialogTitle, dialogContent, dialogType, dialogCallback);

*/

Mangrove.showDialog = function(title, text, type, callback) {
    var ok     = (type & OK)     ? 'ok=&'     : '';
    var yes    = (type & YES)    ? 'yes=&'    : '';
    var no     = (type & NO)     ? 'no=&'     : '';
    var cancel = (type & CANCEL) ? 'cancel=&' : '';
    
    var options = ok + yes + no + cancel;
    
    if (options.length > 0)
        options = '&' + options;
    
    top.showOverlay('../SysForms/Dialog.aspx?m=&title=' + encodeURIComponent(title) + '&message=' + encodeURIComponent(text) + options, null, null, callback);
}


if (typeof($filterDimensions) == 'undefined') {
    $filterDimensions = function(n_win, n_docel, n_body) {
	    var n_result = n_win ? n_win : 0;
	    if (n_docel && (!n_result || (n_result > n_docel)))
		    n_result = n_docel;
	    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
    }
}

if (typeof(getScrollLeft) == 'undefined') {
    getScrollLeft = function() {
	    return $filterDimensions(
		    window.pageXOffset ? window.pageXOffset : 0,
		    document.documentElement ? document.documentElement.scrollLeft : 0,
		    document.body ? document.body.scrollLeft : 0
	    );
    }
}

if (typeof(getScrollTop) == 'undefined') {
    getScrollTop = function() {
	    return $filterDimensions(
		    window.pageYOffset ? window.pageYOffset : 0,
		    document.documentElement ? document.documentElement.scrollTop : 0,
		    document.body ? document.body.scrollTop : 0
	    );
    }
}

if (typeof(window.getWindowHeight) == 'undefined') {
    window.getWindowHeight = function() {
        var w = window;
        var height = -1;
        if (w.innerHeight) { // all except IE
            height = w.innerHeight;
        } else {
            if (w.document.documentElement)
                height = w.document.documentElement.clientHeight;
            else 
                height = w.document.body.clientHeight;
        }
        return height;
    }
}


if (typeof(window.getWindowWidth) == 'undefined') {
    window.getWindowWidth = function() {
        var w = window;
        var width = -1;
        if (w.innerWidth) { // all except IE
            width = w.innerWidth;
        } else {
            if (w.document.documentElement)
                width = w.document.documentElement.clientWidth;
            else 
                width = w.document.body.clientWidth;
        }
        return width;
    }
}



function openHelp(helpCode) {
    SecurePage.onHelp(helpCode);
}




function showAuditActivity(title, trx, ee, contextID, contextString, tableName, msg) {
    trx = trx || '';
    contextID = contextID || '';
    contextString = contextString || '';
    tableName = tableName || '';
    msg = msg || '';
    title = title || '';
    ee = ee || '';
    
    top.showOverlay('../SysForms/ViewActivity.aspx?m=&title=' + encodeURIComponent(title) + '&trx=' + encodeURIComponent(trx) + '&ee=' + ee + '&ci=' + contextID + '&cs=' + encodeURIComponent(contextString) + '&t=' + encodeURIComponent(tableName) + '&msg=' + encodeURIComponent(msg));
}








function RoundedCorners(id, bk, h, tl, tr, bl, br, tries) {
    var el = id;

    if (typeof (tl) == 'undefined') { tl = true; }
    if (typeof (tr) == 'undefined') { tr = true; }
    if (typeof (bl) == 'undefined') { bl = true; }
    if (typeof (br) == 'undefined') { br = true; }
    
    if (typeof (id) == 'string') {
        el = document.getElementById(id);
    }
    
    if (el == null) {
        if (tries == null) tries = 200;
        if (tries > 0)
            setTimeout("RoundedCorners('" + id + "','" + bk + "'," + h + "," + (--tries) + ")", 50);
        return;
    }

    var topLeft, topRight, bottomLeft, bottomRight;

    if (tl) {
        topLeft = document.createElement("b");
        topLeft.style.display = "block";
        topLeft.style.height = h + "px";
        topLeft.style.fontSize = "1px";
        topLeft.style.background = "url(" + bk + ") no-repeat 0 0";
    }

    if (tr) {
        topRight = document.createElement("b");
        topRight.style.display = "block";
        topRight.style.height = h + "px";
        topRight.style.fontSize = "1px";
        topRight.style.background = "url(" + bk + ") no-repeat 100% -" + h + "px";
    }

    if (bl) {
        bottomLeft = document.createElement("b");
        bottomLeft.style.display = "block";
        bottomLeft.style.height = h + "px";
        bottomLeft.style.fontSize = "1px";
        bottomLeft.style.background = "url(" + bk + ") no-repeat 0 -" + (2 * h) + "px";
    }

    if (br) {
        bottomRight = document.createElement("b");
        bottomRight.style.display = "block";
        bottomRight.style.height = h + "px";
        bottomRight.style.fontSize = "1px";
        bottomRight.style.background = "url(" + bk + ") no-repeat 100% -" + 3 * h + "px";
    }
    
    /*
    for (var i = 0; i < 4; i++) {
        c[i] = document.createElement("b");
        c[i].style.display = "block";
        c[i].style.height = h + "px";
        c[i].style.fontSize = "1px";
        
        //left
        if (i % 2 == 0) {
            c[i].style.background = "url(" + bk + ") no-repeat 0 -" + i * h + "px";
        } else {
            //right
            //c[i].style.background = "url(" + bk + ") no-repeat 100% -" + i * h + "px";
        }
    }
    */
    
    if (topLeft) {
        if (topRight) {
            topLeft.appendChild(topRight);
        }
    }

    if (bottomLeft) {
        if (bottomRight) {
            bottomLeft.appendChild(bottomRight);
        }
    }

    el.style.padding = "0";

    if (topLeft) {
        el.insertBefore(topLeft, el.firstChild);
    } else if (topRight) {
        el.insertBefore(topRight, el.firstChild);
    }

    if (bottomLeft) {
        el.appendChild(bottomLeft);
    } else if (bottomRight) {
        el.appendChild(bottomRight);
    }
}


function applyRoundCorners(className, imageName, topLeft, topRight, bottomLeft, bottomRight) {

    var elements = $getElementsByClassName(document, null, className);
    
    for (var i = 0; i < elements.length; ++i) {
        if (elements[i]) {
            RoundedCorners(elements[i], imageName, 5, topLeft, topRight, bottomLeft, bottomRight);
        }
    }
}

_RoundedCornerImages = {
    'round': '../images/light-gray-5px.png',
    'round-gray': '../images/light-gray-5px.png',
    'round-red': '../images/light-red-5px.gif',
    'round-yellow': '../images/light-yellow-5px.png',
    'round-blue': '../images/light-blue-5px.png',
    'round-green': '../images/light-green-5px.gif'
};

_RoundedCornerTypes = {
    'all': [ true, true, true, true ],
    'top': [ true, true, false, false ],
    'bottom': [ false, false, true, true ],
    'left': [ true, false, true, false ],
    'right': [ false, true, false, true ],
    'top-left': [ true, false, false, false ],
    'top-right': [ false, true, false, false ],
    'bottom-left': [ false, false, true, false ],
    'bottom-right': [ false, false, false, true ],
    'top-bottom-left': [ true, true, true, false ],
    'top-bottom-right': [ true, true, false, true ],
    'top-left-bottom-right': [ true, false, false, true ],
    'top-right-bottom-left': [ false, true, true, false ],
    'top-right-bottom': [ false, true, true, true ],
    'top-left-bottom': [ true, false, true, true ]
};


$addLoadEvent(function() {
    //setTimeout(function() {
        for (var className in _RoundedCornerImages) {
            for (var cornerType in _RoundedCornerTypes) {
                applyRoundCorners(
                className + '-' + cornerType,
                _RoundedCornerImages[className],
                _RoundedCornerTypes[cornerType][0],
                _RoundedCornerTypes[cornerType][1],
                _RoundedCornerTypes[cornerType][2],
                _RoundedCornerTypes[cornerType][3]
            );
            }
        }
    //}, 1);
});



function fireDefaultButton(event, target) {
    if (event.keyCode == 13) {
        var src = event.srcElement || event.target;
        
        if (!src || (src.tagName.toLowerCase() != "textarea")) {
            var defaultButton = document.getElementById(target);
            
            if (defaultButton && typeof(defaultButton.click) != "undefined") {
                defaultButton.click();
                event.cancelBubble = true;
                if (event.stopPropagation) event.stopPropagation();
                return false;
            }
        }
    }
    
    return true;
}




function parsePageName() {
    var startIndex = window.location.toString().indexOf('SysForms/');
    var url = window.location.toString().substr(startIndex + 9);
    var aspxIndex = url.indexOf('.aspx');
    
    url = url.substring(0, aspxIndex);
    
    return url;
}

//global reference for help window
Mangrove.HelpWindow = null;

//help event handler
Mangrove.onHelp = function() {

    var helpContextID = parsePageName();

    //create a function that wraps the window.open and assignment of the global window context variable (ValidationPage.HelpWindow)
    var createHelpWindow = function() {
        Mangrove.HelpWindow = window.open('../SysForms/Help.aspx?id=' + helpContextID, 'MangroveHelpWindow', 'location=0, resizable=1, scrollbars=1');
    }

    createHelpWindow();

    return false;
    //if the window exists, try to focus it, if that fails, invoke our create function. If the window doesn't exist, create it!
    if (typeof (Mangrove.HelpWindow) != 'undefined' && Mangrove.HelpWindow != null) {
        try {
            Mangrove.HelpWindow.focus();
        } catch (ex) {
            createHelpWindow();
        }
    } else {
        createHelpWindow();
    }

    return false;
}


window.onhelp = Mangrove.onHelp;



window.onkeypress = function(event) {
    if (FIREFOX) {
        if ((window.event || event).keyCode == 112) {
            Mangrove.onHelp();

            if (event.stopPropagation)
                event.stopPropagation();

            if (event.preventDefault)
                event.preventDefault();

            return false;
        }
    }
}




function getDocumentHeight() {
    var d = document;
    return Math.max(
        Math.max(d.body.scrollHeight, d.documentElement.scrollHeight),
        Math.max(d.body.offsetHeight, d.documentElement.offsetHeight),
        Math.max(d.body.clientHeight, d.documentElement.clientHeight)
    );
}

function getDocumentWidth() {
    var d = document;
    return Math.max(
        Math.max(d.body.scrollWidth, d.documentElement.scrollWidth),
        Math.max(d.body.offsetWidth, d.documentElement.offsetWidth),
        Math.max(d.body.clientWidth, d.documentElement.clientWidth)
    );
}



function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}