// Detect if we're dealing with a decent browser with DOM Level 2 Event Model support.
if (!navigator || (document.addEventListener == null && document.attachEvent == null))
    window.location.href = baseURL + "/errors/bad_browser.aspx?offender=browser";
    
// We also need to rule out Internet Explorer/Win 5.0. Enough of this junk.
if (/MSIE 5.0/i.test(navigator.appVersion))
    window.location.href = baseURL + "/errors/bad_browser.aspx?offender=browser";

if (!navigator.cookieEnabled)
    window.location.href = baseURL + "/errors/bad_browser.aspx?offender=cookies";

/* --------------------  Misc Utilities  -------------------------*/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

//------------------------------------------------------------
function getFirstChildByTagName (node, tagName)
{
	var testNode = node.firstChild;

	while (testNode)
	{
		if ((testNode.tagName != null) && (testNode.tagName.toLowerCase() == tagName.toLowerCase ()))
			return testNode;
		else
			testNode = testNode.nextSibling;
	}
	
	return null;
}

// Cancel bubble
function cancelEvent(e)
{
  if (!e) e = event;
  e.cancelBubble = true;
}

// ----------------------------------------------------------------
function CfcNamespace () {}

CfcNamespace.Resources = new function () {
    var _strings = {};
    
    function _registerResource (r_key, r_value) { 
        if (!_strings [r_key])
            _strings [r_key] = r_value;
    }
    
    function _getResource (r_key) {
        return _strings [r_key];
    }
    
    return {
        RegisterResource : function (r_key, r_value) { return _registerResource (r_key, r_value); },
        GetResource :      function (r_key)          { return _getResource (r_key); }
    };
}


// Verify the length of text being pasted
// does not exceed the length specified
function checkPasteLength (oEl, iLen)
{
    // Sanity check
    if (null == oEl || oEl.type != 'textarea') return false;
    
    if (oEl.value.length < iLen)
    {
        var oCb = window.clipboardData.getData("Text");
        var sText = oEl.value + oCb;
        oEl.value = sText.substring(0,iLen)
    }
    return false;
}

// ----------------------------------------------------------------

// Trim leading and trailing spaces
function stringTrim (strStr)
{
    if (strStr == null)
        return "";

    strStr = strStr.replace (/^\s+/, "");
    strStr = strStr.replace (/\s+\$/, "");
    return strStr;
}

// ------------------------------------------------------------

// Check if a string is empty
function IsEmpty (strStr) {
  return (Boolean) (strStr == null || (String) (stringTrim (strStr)).length == 0);
}

// ----------------------------------------------------------------

// Simulate clicking on the first child anchor tag found
function followLink (node) {
    var lnk = getFirstChildByTagName (node, "a");
    
    if (lnk != null)
        self.location.href = lnk.href;
}

// ----------------------------------------------------------------

function addClassName(el, name)
{
	// Remove the class name if it already exists in the element's class name
	// list.

	removeClassName(el, name);

	// Add the class name to the element's current list of class names.

	if (el.className.length > 0)
		name = " " + name;
	el.className += name;
}

function removeClassName(el, name)
{
	// If the element has no class names, exit.

	if (el.className == null)
		return;

	// Rebuild the list of class names on the element but exclude the specified
	// class name.

	var newList = new Array();
	var curList = el.className.split(" ");
	for (var i = 0; i < curList.length; i++)
		if (curList[i] != name)
			newList.push(curList[i]);
	el.className = newList.join(" ");
}


// *****
/* --------------------  Window  Library  -------------------------*/
// *****

function openNewWindow (url, parmWidth, parmHeight, paramName)
{
	var x = screen.width;
	var y = screen.height;
	var windowName = (null == paramName) ?  'win' + Math.floor (Math.random() * 9999) : paramName;
	
	// We target the worst case scenario: 800x600. Therefore the max width of our canvas in 760 pixes
	var winWidth = (null == parmWidth) ? 787 : parmWidth;
	var winHeight = (null == parmHeight) ? (y * 0.7) : parmHeight;
    var winLeft = (x - winWidth) / 2;
	var winTop = (y - winHeight) / 2;
	
	
	var openStr = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=' + winWidth + ', height=' + winHeight; //+', left=' + winLeft + ', top=' + winTop;
	newwin = window.open (url, windowName, openStr);
	if(parseInt(navigator.appVersion) >= 4 && newwin != null)
 		newwin.focus();
 		
 	if (newwin == null)
 	    alert(popUpBlockerAlert);
}

function openNewDialog (url, parmWidth, parmHeight, paramName)
{
	var x = screen.width;
	var y = screen.height;
	var windowName = (null == paramName) ?  'win' + Math.floor (Math.random() * 9999) : paramName;
	
	// We target the worst case scenario: 800x600. Therefore the max width of our canvas in 760 pixes
	var winWidth = (null == parmWidth) ? 787 : parmWidth;
	var winHeight = (null == parmHeight) ? (y * 0.7) : parmHeight;
    var winLeft = (x - winWidth) / 2;
	var winTop = (y - winHeight) / 2;
	
	
	var openStr = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=' + winWidth + ', height=' + winHeight; //+', left=' + winLeft + ', top=' + winTop;
	newwin = window.open (url, windowName, openStr);
	if(parseInt(navigator.appVersion) >= 4 && newwin != null)
 		newwin.focus();
 		
 	if (newwin == null)
 	    alert(popUpBlockerAlert);
}

// *****
/* --------------------  Server Control Helpers  -------------------------*/
// *****

function changeVisibility (controlID, action)
{
    if (null == document.getElementById (controlID))
        return;

    var imagePath
    var controlState = document.getElementById (controlID).style.display;
         
    if (action == null)
        controlState = (controlState == 'block' || controlState == '') ? 'none' : 'block';
    else
        controlState = (action == 1) ? 'block' : 'none';
        
    if (document.getElementById (controlID).style.display == controlState)
        return;
    
    imagePath = document.getElementById (controlID + '_img').src;

    if (imagePath.search ('minus.gif') != -1)
 	    imagePath = imagePath.replace (/minus.gif/i, 'plus.gif');
	else
	    imagePath = imagePath.replace (/plus.gif/i, 'minus.gif');
    	
    document.getElementById (controlID + '_img').src = imagePath;
    document.getElementById (controlID).style.display = controlState;
}

// ----------------------------------------------------------------
// Toggle all checkboxes of a list control.
// 
// switcher - a "Select/deselect all" type of button (control)
// listControl - a checkbox list control ID (string)
// fcallback - an optional callback (function)
// ----------------------------------------------------------------
function SelectAllToggles (switcher, listControl, fcallback)
{
    var roleSelections = document.getElementById (listControl);
    var inputs = roleSelections.getElementsByTagName ('input');

    for (var i=0; i<inputs.length; i++)
    {
        if (inputs[i].type == "checkbox" && !inputs[i].disabled)
            inputs[i].checked = switcher.checked;
    }

    if (fcallback != null && (typeof(fcallback) == "function"))
        fcallback ();
}


// ----------------------------------------------------------------
function CenterUploadArea(container)
{
    function offsetParent (element) {
        if (element.offsetParent) return element.offsetParent;
        if (element == document.body) return element;

        while ((element = element.parentNode) && element != document.body)
        if (Element.getStyle(element, 'position') != 'static')
            return element;

        return document.body;
    }  
      
    var uploadContainer = null;
    
    if (CenterUploadArea.container)
    {
        uploadContainer = CenterUploadArea.container;
    }
    else
    {
        if (!container)
        {
            var divs = document.getElementsByTagName ('DIV');
            for (var i=0; i<divs.length; i++)
            {
                if (divs[i].className == 'RadUploadProgressArea')
                {
                    uploadContainer = divs[i];
                    break;
                }
            }
        }
        else
            uploadContainer = document.getElementById (container);
            
        CenterUploadArea.container = uploadContainer;
    }
    
    if (!uploadContainer)
        return;
    
    var posContainer = offsetParent (uploadContainer);
    posContainer.style.position = 'static';
    
    var scrollX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
    var scrollY = window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop;
    
    var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    var windowWidth  = window.innerWidth  || document.documentElement.clientWidth  || document.body.clientWidth;
    
    var x = Math.round (windowWidth/2 - uploadContainer.offsetWidth/2) + scrollX;
    var y = Math.round (windowHeight/2 - uploadContainer.offsetHeight/2) + scrollY;
    
    uploadContainer.style.top = y + 'px';
    uploadContainer.style.left = x + 'px';
    uploadContainer.style.position = 'absolute';
}

// ----------------------------------------------------------------
function displayProgressArea (anchorId) {
    var progress = $get ('progress-area');
    var x = 0, y =0;
    var h = 0, w = 0;
    var image = null;
    
        
    if (!progress)
    {
        progress = document.createElement ('div');
        
        $(progress)
            .css ({
                position : 'absolute',
                border : '1px solid #e0e0e0',
                zIndex : '9999',
                verticalAlign : 'middle',
                overflow : 'hidden'
            })
            .attr ('id', 'progress-area')
            .addClass ('select_free__')
            .appendTo (document.body);
    }

    if (!anchorId)
    {
        w = 130 + 80;
        h = 60 + 80;
        image = 'loading_large.gif';
        
        var scrollX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
        var scrollY = window.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop;
        
        var windowHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        var windowWidth  = window.innerWidth  || document.documentElement.clientWidth  || document.body.clientWidth;
        
        x = Math.round (windowWidth/2 - w/2) + scrollX;
        y = Math.round (windowHeight/2 - h/2) + scrollY;
    }
    else
    {
        var bounds = Sys.UI.DomElement.getBounds ($get (anchorId));
        x = bounds.x; y = bounds.y;
        h = bounds.height; w = bounds.width;
        image = (h < 60) ? 'loading.gif' : 'loading_large.gif';
    }

    $(progress).empty ();
    
    var ind = document.createElement ('img');
    $(ind)
        .attr ('src', baseURL + '/images/' + image)
        .appendTo (progress);
        
    var mt = -1 * (ind.offsetHeight/2) + 'px';
    var ml = -1 * (ind.offsetWidth/2) + 'px';
    
    $(ind)
        .css ({
            position : 'absolute',
            top : '50%',
            left : '50%',
            marginTop : mt,
            marginLeft : ml
        });
    
    var frameKludge = document.createElement ('iframe');
    $(frameKludge)
        .attr ('src', baseURL + '/blank__.html')
        .appendTo (progress)
        .css ({
            display : 'block',
            position : 'absolute',
            top : '0',
            left : '0',
            zIndex : '-1',
            filter : 'mask()',
            width : '3000px',
            height : '3000px',
            border : 'none',
            overflow : 'hidden'
        });

    $(progress)
        .css ({        
            background : '#fff',
            width :  w + 'px',
            height : h + 'px',
            left : x + 'px',
            top : y + 'px'
         })
         .show ();
}

// -------------------------------------------------------------
function hideProgressArea () {
    document.body.removeChild ($get('progress-area'));
}

// -------------------------------------------------------------
function showUserProfileWindow (userId, openerId) 
{
    var oManager  = GetRadWindowManager ();
    var oWnd      = oManager.GetWindowByName ("UserProfileSnapshotWindow");
    var position  = Sys.UI.DomElement.getLocation ($get (openerId));
    
    oWnd.SetUrl (baseURL + "/members/admin/user_details_snapshot.aspx?id=" + userId);
    oWnd.Show ();
    
    oWnd.MoveTo (position.x + 20, position.y);
    oWnd.SetSize (320, 250);
}
