//=============================================================================
//
//  Core.js
//		This file contains JavaScript functions to handle the core common  
//		client-side functions 
//
//=============================================================================
var UNDEF='undefined';

function fadeElementIn(oel,duration){
	if(!oel){return}
	if(typeof(oel.style)!=UNDEF){
		if(typeof(oel.style.filter)!=UNDEF){
			oel.style.display="none";oel.style.visibility="hidden";
			oel.style.filter="progid:DXImageTransform.Microsoft.Fade(duration="+duration+")";oel.filters[0].Apply();
			oel.style.visibility="visible";oel.style.display="inline";oel.style.zIndex=999;
			oel.filters[0].Play();
		}else{oel.style.visibility="visible";oel.style.display="inline";}
	}
}
function showIt(oel){if(typeof(oel)!=UNDEF&&oel!=null&&typeof(oel.style)!=UNDEF){oel.style.visibility="visible";oel.style.display="inline";}}

function hideIt(oel){if(typeof(oel)!=UNDEF&&oel!=null&&typeof(oel.style)!=UNDEF){oel.style.visibility="hidden";oel.style.display="none";}}

function getAbsPos(el){
	var offsetTrail=el;var offsetLeft=0;var offsetTop=0;
	while(offsetTrail){offsetLeft+=offsetTrail.offsetLeft;offsetTop+=offsetTrail.offsetTop;offsetTrail=offsetTrail.offsetParent;}
	if(navigator.userAgent.indexOf("Mac")!=-1&&typeof(document.body.leftMargin)!=UNDEF){offsetLeft+=document.body.leftMargin;offsetTop+=document.body.topMargin;}
	return {left:offsetLeft,top:offsetTop};
}

function getElement(id){
    var d=document;
    return d.getElementById?d.getElementById(id):d.all?d.all[id]:d.layers[id];
}

function browseURL(sURL){
    window.open(sURL,'browsePreview');
    return;
}

function browseURLSelf(sURL){
    window.open(sURL,'_self');
    return;
}

function popupURL(sURL){
    window.open(sURL,'_blank');
    return;
}

function confirmPrompt(PostBackToCtlName,PostBackEventArg,prompt){
   var confirmed = window.confirm(prompt);
   if (confirmed) {javascript:__doPostBack(PostBackToCtlName,PostBackEventArg)}
}

var iGallerySelectedID =0

function galleryRadioSelected(radio, recID){

	iGallerySelectedID = recID

	unCheckOtherDGRadios(radio);

	if (window.OnGalleryRadioSelected) {
		//allow local handlers to play
		window.OnGalleryRadioSelected(recID)
	}

}

function unCheckOtherCBsInColumn(chk)
{
    if (chk.checked)
    {
        var otherChks = chk.parentNode.parentNode.parentNode.getElementsByTagName('input');
        var rowCount = otherChks.length;
        for (var index = 0; index < rowCount; index++)
        {
            var elem = otherChks[index];
            if ((elem != null) && (elem != chk) && (elem.parentNode != null) && chk.parentNode.cellIndex == elem.parentNode.cellIndex)
            {
                elem.checked = false;
            }
        }
    }
}

function unCheckOtherDGRadios(radio){
	var otherRadios=radio.parentNode.parentNode.parentNode.getElementsByTagName('input');
	var rowCount = otherRadios.length;
	var index;
	var elem;
	for (index=0;index<rowCount;index++){
		elem=otherRadios[index];
		if ((elem != null) && (elem != radio)){elem.checked = false;}
	}
}


function Page_BBValidate(ValidationGroup) {

    var i;
    var j=0;

	if (typeof(Page_Validators)!=UNDEF){
		var Temp = Page_Validators;
		Page_Validators=new Array();

		for (i = 0; i < Temp.length; i++) {
			if (typeof(Temp[i].ValidationGroup)!=UNDEF&&Temp[i].ValidationGroup==ValidationGroup) {
				if(!Temp[i].disabled){Page_Validators[j]=Temp[i];j++;}
			}
		}
	}
	if (typeof(Page_ValidationSummaries)!=UNDEF){
		var Temp2 = Page_ValidationSummaries;
		Page_ValidationSummaries=new Array();
		
		j=0;
		for (i = 0; i < Temp2.length; i++) {
			if (typeof(Temp2[i].ValidationGroup)!=UNDEF&&Temp2[i].ValidationGroup==ValidationGroup) {
				Page_ValidationSummaries[j]=Temp2[i]
				j++;
			}
		}
	}
	var bret=true;
	if (typeof(Page_ClientValidate)=='function'){
		bret=Page_ClientValidate();
	}	
	if (typeof(Page_Validators)!=UNDEF){Page_Validators=Temp};
	if (typeof(Page_ValidationSummaries)!=UNDEF){Page_ValidationSummaries=Temp2};
	
	return bret	
	
}


var TemplateMsgElement;
var TemplateProcessingElement;
var TemplateContentElement;
var TemplateRepeatElement;
var savePostBackFunc;
var noPostBacks=false;
var saveEventTarget;
var saveEventArgument;

function ForcePostBack(){
    noPostBacks=false;
    return BBProcMsg(saveEventTarget,saveEventArgument);
}

function BBProcMsg(eventTarget, eventArgument){

	var omsg=TemplateMsgElement;var smsg;
	if(typeof(window.event) != UNDEF && window.event != null && typeof(window.event.srcElement)!= UNDEF && window.event.srcElement!=null){
	    smsg=window.event.srcElement.processingmsg;
	};

	if(typeof(savePostBackFunc)=='function'){
		if(!noPostBacks){
			noPostBacks=true;
			if( omsg && typeof(smsg) != UNDEF && smsg!=null) {
			    omsg.innerHTML=smsg+', please wait&nbsp;...';
			};
			
			savePostBackFunc(eventTarget, eventArgument);
			
			hideIt(TemplateContentElement);
			hideIt(TemplateRepeatElement);
			showIt(TemplateProcessingElement);
		}else{
			saveEventArgument=eventArgument;saveEventTarget=eventTarget;			
			showIt(TemplateRepeatElement);
		};
	};
};

function makeHot(oel,hotClass){
	if(typeof(oel.saveClassName)==UNDEF){
	    oel.saveClassName=oel.className;
	    oel.onmouseout=function(){
	        this.className=this.saveClassName;
	    };
	};
	if(typeof(hotClass)==UNDEF){
	    oel.className=oel.saveClassName+"Hot";
	}
	else{
	    oel.className=hotClass;
	};		
}
function hotImg(oel,hotImgSrc){
	if(typeof(oel.saveSrc)==UNDEF){
		oel.saveSrc=oel.src;
		oel.onmouseout=function(){
			if(this.src!=this.saveSrc){
				this.src=this.saveSrc
			}
		}
	};
	if(oel.src!=hotImgSrc){
		oel.src=hotImgSrc;
	};
}
function killEvent(){
    try 
    {
        if (window.event)
        {
            window.event.cancelBubble = true;
        }
    } 
    catch(e){
    }
    return false;
}

//Was in 5.0 & 5.1, yet not in 5.5
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

// Removes leading whitespaces
function LTrim( value ) 
{
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

// Removes ending whitespaces
function RTrim( value ) 
{
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function trim( value ) 
{
	return LTrim(RTrim(value));
}



function AddBorderToPaddedElement(elt, borderStyle, paddingWithBorder) {
    elt.style.border = borderStyle
    elt.style.padding = paddingWithBorder
}

function RemoveBorderFromPaddedElement(elt, paddingWithoutBorder) {
    elt.style.border = ''
    elt.style.padding = paddingWithoutBorder
}

function select_AddOption(selectControl, optionText, optionValue)
{
    var o = new Option(optionText, optionValue);
    o.Value = optionValue; // this is an object; "value" is a string
    selectControl.options.add(o);
}

function select_GetSelectedText(selectControl)
{
    if (selectControl.selectedIndex >= 0)
        return selectControl.options[selectControl.selectedIndex].text;
}

function select_GetSelectedStringValue(selectControl)
{
    if (selectControl.selectedIndex >= 0)
        return selectControl.options[selectControl.selectedIndex].value;
}

function select_GetSelectedObjectValue(selectControl)
{
    if (selectControl.selectedIndex >= 0)
        return selectControl.options[selectControl.selectedIndex].Value;
}

function newid()
{
    var result = '';
    for(var j=0; j<32; j++)
    {
        if( j == 8 || j == 12|| j == 16|| j == 20)
            result = result + '-';
        result = result + Math.floor(Math.random()*16).toString(16).toUpperCase();
    }
    return result;
}

function iframe_GetDocument(iframe)
{
    if (document.all) // IE
    {
        iframe = eval(iframe.id);
        return iframe.document;
    }
    else
    {
        return iframe.contentWindow.document;
    }
}

function isNumeric(str) {
    return str.length ? !isNaN(str/1) : false;
}

function repeatString(string, count)
{
    var temp = new Array(count+1);
    return temp.join(string);
}

// CHF: Making this a function allows one to override it.
function DisableMe(sender)
{
    sender.disabled = true;
}

function getMousePosition(e)
{
    var pos = new Object();
    if (isIE)
    {
        pos.x = event.clientX + document.body.scrollLeft;
        pos.y = event.clientY + document.body.scrollTop;
    }
    else
    {
        pos.x = e.clientX;
        pos.y = e.clientY;
    }
    return pos;
}

function PopUpDialogBB(controlName, sName, sFeatures, queryStringData, bHideCss){
	//controlName is the user control to load - use the ~/path syntax
	//sName is name of window use _blank for new window
	//sFeatures is the features for the new window
	//queryStringData is a string and is passed as-is on the query string and handed to your ctl's IBBDialog.data property
	//bHideCss is a boolean whether to include a StyleSheet in the page render - Nothing or 0 (default) will use a Css
	this.ctl = controlName
	this.name = sName
	this.features = sFeatures
	this.qsdata = queryStringData
	this.Show = Show
	this.HideCss = bHideCss
		
	function Show(){
		if(typeof(this.ctl)==UNDEF)	  {alert("PopUpDialogBB assert: ctl parameter not set in arg object")}
		var url = ROOT_PATH + "PopUp.aspx?ctl="+this.ctl+"&data="+this.qsdata+"&hidecss="+this.HideCss;
		var popwin = window.open(url,this.name,this.features);
		if( typeof(popwin) != "undefined" && popwin )
		{
			popwin.focus();
		}
	}
}

/////////////////////////////////////////////////////////////////////////
// These functions counteract a memory leak in IE (and are harmless in other browsers)
// See http://javascript.crockford.com/memory/leak.html

// Shouldn't need to call this directly
function purge(d) {
    var a = d.attributes, i, l, n;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            n = a[i].name;
            if (typeof d[n] === 'function') {
                d[n] = null;
            }
        }
    }
    purgeChildren(d);
}

// Shouldn't need to call this directly
function purgeChildren(d) {
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
    }
}

// Call this instead of setting innerHTML directly
function setInnerHTML(element, value) {
    if (isIE)
    {
        purgeChildren(element);
    }
    element.innerHTML = value;
}

// Call this instead of calling the parent's removeChild directly
function removeChild(parent, child) {
    if (isIE)
    {
        purge(child);
    }
    return parent.removeChild(child);
}

// Call this instead of calling the parent's replaceChild directly
function replaceChild(parent, newChild, oldChild) {
    if (isIE)
    {
        purge(oldChild);
    }
    return parent.removeChild(newChild, oldChild);
}

/////////////////////////////////////////////////////////////////////////

function removeClass(element, className)
{
    element.className = (" " + element.className + " ").replace(" " + className + " ", " ").trim();
}
function addClass(element, className)
{
    element.className += (element.className ? " " : "") + className;
}
function replaceClass(element, oldClassName, newClassName)
{
    element.className = (" " + element.className + " ").replace(" " + oldClassName + " ", " " + newClassName + " ").trim();
}
function hasClass(element, className)
{
    return (" " + element.className + " ").indexOf(" " + className + " ") >= 0;
}

function bbAdminButton_setDisabled(buttonElement, disabled)
{
    var href;
    if (disabled)
    {
        replaceClass(buttonElement, "BBAdminButton", "BBAdminButtonDisabled");
        buttonElement.style.filter = "alpha(opacity=40)";
        buttonElement.style.MozOpacity = 0.5;
        cursor = "default";
    }
    else
    {
        replaceClass(buttonElement, "BBAdminButtonDisabled", "BBAdminButton");
        buttonElement.style.filter = "alpha(opacity=100)";
        buttonElement.style.MozOpacity = 1.0;
        cursor = "hand";
    }
    walkDom(buttonElement, function (element) {
        if (element.tagName === "A")
        {
            element.style.cursor = cursor;
        }
    });
}

function image_setDisabled(img, disabled)
{
    if (disabled)
    {
        img.style.cursor = "auto";
        img.style.filter = "alpha(opacity=40)";
        img.style.MozOpacity = 0.5;
    }
    else
    {
        img.style.cursor = "hand";
        img.style.filter = "alpha(opacity=100)";
        img.style.MozOpacity = 1.0;
    }
}

function createEnum(namspace, enumName, enumEntries)
{
    /*
    // Some examples using createEnum():
    
    var myEnums = {};
    
    createEnum(myEnums, "Weekend", [
        [0, "Saturday"],
        [1, "Sunday"]
    ]);
    createEnum(myEnums, "Weekend", [
        ["Saturday"],
        ["Sunday"]
    ]);
    createEnum(myEnums, "Weekend", [
        "Saturday",
        "Sunday"
    ]);
    // The three function calls above are equivalent and result in the following truths:
    // myEnums.Weekend.Saturday === 0
    // myEnums.WeekendText[0] === "Saturday"
    // etc.
    
    createEnum(myEnums, "Buttons", [
        [1, "OK", "Yes, this is OK."],
        [2, "Cancel", "Cancel my request."],
        [4, "Retry", "Retry the request."],
        [8, "Help", "Help!"]
    ]);
    // The function call above results in the following truths:
    // myEnums.Buttons.OK === 1
    // myEnums.ButtonsText[1] === "Yes, this is OK."
    // etc.
    
    // More examples in Query.js
    */
    var enumObj = namspace[enumName] = {};
    var textObj = namspace[enumName + "Text"] = {};
    for (var i = 0; i < enumEntries.length; i++)
    {
        var enumEntry = enumEntries[i];
        if (enumEntry)
        {
            if (typeof enumEntry === 'string')
            {
                enumObj[enumEntry] = i;
                textObj[i] = enumEntry;
            }
            else
            {
                var enumValue, enumSymbolIndex;
                if (typeof enumEntry[0] === 'number')
                {
                    enumValue = enumEntry[0];
                    enumSymbolIndex = 1;
                }
                else
                {
                    enumValue = i;
                    enumSymbolIndex = 0;
                }
                var symbol = enumEntry[enumSymbolIndex];
                var text = enumEntry[(enumEntry.length > enumSymbolIndex) ? enumSymbolIndex + 1 : enumSymbolIndex];
                enumObj[symbol] = enumValue;
                textObj[enumValue] = text;
            }
        }
    }
}

// Calls workerFunction on element and every child (recursive), aborts when workerFunction returns false
function walkDom(element, workerFunction)
{
    if (workerFunction(element) !== false)
    {
        for (var i = 0; i < element.childNodes.length; i++)
        {
            if (!walkDom(element.childNodes[i], workerFunction))
            {
                return false;
            }
        }
        return true;
    }
    return false;
}

// Put "evt = getEvent(evt);" at the begining of each event handler that takes an event argument
function getEvent(evt)
{
    evt = evt || event;
    evt.target = evt.target || evt.srcElement;
    return evt;
}

// Much faster than eval(objectName)
function getObject(objectName, allowUndefinedFunction)
{
    try
    {
        var parts = objectName.split('.');
        var reference = window;
        for (var i = 0; i < parts.length; i++)
        {
            reference = reference[parts[i]];
        }
        if (reference || allowUndefinedFunction)
        {
            return reference;
        }
    }
    catch (e) { }

    throw new Error(String.format("Object does not exist: '{0}'", objectName));
}

function TabInTextArea(event, obj) {

    //usage: <textarea onkeydown="return TabInTextArea(event, this);" .../>
    var tabKeyCode = 9;

    if (event.which) // mozilla
        var keycode = event.which;
    else // ie
        var keycode = event.keyCode;

    if (keycode == tabKeyCode) {
        if (event.type == "keydown") {
            if (obj.setSelectionRange) {
                // mozilla
                var s = obj.selectionStart;
                var e = obj.selectionEnd;
                obj.value = obj.value.substring(0, s) + 
                    "\t" + obj.value.substr(e);
                obj.setSelectionRange(s + 1, s + 1);
                obj.focus();
            } else if (obj.createTextRange) {
                // ie
                document.selection.createRange().text="\t"
                obj.onblur = function() { this.focus(); this.onblur = null; };
            } else {
                // unsupported browsers
            }
        }
        if (event.returnValue) // ie ?
            event.returnValue = false;
        if (event.preventDefault) // dom
            event.preventDefault();
        return false; // should work in all browsers
    }
    return true;
}

function toggleDisabledById(ctrlId)
{
    var ctrl = document.getElementById(ctrlId);
    ctrl.disabled = !(ctrl.disabled);
}

function setDisabledById(ctrlId, disabled)
{
    var ctrl = document.getElementById(ctrlId);
    
    if(ctrl)
    {
        ctrl.disabled = disabled;
    }
}

function setDisabledByIds(ctrlIds, disabled)
{
    if(ctrlIds && ctrlIds.length)
    {
        for(var i = 0; i < ctrlIds.length; i++)
        {
            setDisabledById(ctrlIds[i], disabled);
        }
    }
}

function setFauxDisabledById(ctrlId, disabled)
{
    var color = (disabled ? "gray" : "");
    
    setStyleAttributeById(ctrlId, "color", color);
}

function setFauxDisabledByIds(ctrlIds, disabled)
{
    if(ctrlIds && ctrlIds.length)
    {
        for(var i = 0; i < ctrlIds.length; i++)
        {
            setFauxDisabledById(ctrlIds[i], disabled);
        }
    }
}

function setStyleAttributeById(ctrlId, styleAttribute, styleValue)
{
    var ctrl = getElement(ctrlId);
    
    if(ctrl && ctrl.style)
    {
        ctrl.style[styleAttribute] = styleValue;
    }
}

function swapStyleAttributeByIds(ctrl1Id, ctrl2Id, styleAttribute)
{
    var ctrl1 = getElement(ctrl1Id);
    var ctrl2 = getElement(ctrl2Id);
    
    if(ctrl1 && ctrl1.style && ctrl2 && ctrl2.style)
    {
        // If they have style, they should have currentStyle
        var style1 = ctrl1.currentStyle[styleAttribute];
        
        // Could use setStyleAttributeById, but to save a few cycles from re-getting the element,
        // we'll do it here
        ctrl1.style[styleAttribute] = ctrl2.currentStyle[styleAttribute];
        ctrl2.style[styleAttribute] = style1;
    }
}

// Parameters:
//    url - string containing the url to convert
//
// Returns:
//    string containing the converted url to
//    match the protocol of the current document
function convertToCurrentProtocol(url)
{
    if(url && url.replace)
    {
        url = url.replace(/http[s]?:/i, document.location.protocol);
    }
    
    return url;
}

function setChildrenDisabledById(ctrlId, disabled)
{
    var ctrl = document.getElementById(ctrlId);
    walkDom(ctrl, function (element)
    {
        if (element.disabled !== undefined)
        {
            element.disabled = disabled;
        }
    });
}

function resetScrollPositionElements()
{
   //Clear position stored due to MaintainScrollPositionOnPostback	
   var scrollX = document.getElementById('__SCROLLPOSITIONX');
   var scrollY = document.getElementById('__SCROLLPOSITIONY');
   if(scrollX && scrollY)
   {
      scrollX.value = 0;
      scrollY.value = 0;
   }
   
   //Clear position stored due to Ajax scripts
   Sys.WebForms.PageRequestManager.getInstance()._scrollPosition = null;
   
   //Actively scroll to the top.  IE seems to require this
   scrollTo(0,0);
}

//src = full href, which will already include the bb.analytics portion
//This allows pages to manually update the iframe
//Now jQueryfied
function refreshAnalyticsFrame(pagekeys, pagevals, src) {

    var trackingString = src;
    if (!trackingString) {
        trackingString = "bb.analytics?";
        if (pagekeys.length > 0) {
            var aKeys = pagekeys.split(";");
            var aVals = pagevals.split(";");
            var aCount = 0;
            while (aCount < aKeys.length) {
                trackingString += "&" + aKeys[aCount] + "=" + aVals[aCount];
                aCount += 1;
            }
        }
        if (isIE) {
            trackingString = trackingString.substring(0, 2000);
        }
    }

    var IFrameDiv = $('#BBAnalyticsIFrameCell');

    var analyticFrame = $('#BBAnalyticsIFrame');

    //Need to create the iframe
    if (analyticFrame.length == 0) {
        analyticFrame = $(document.createElement("IFRAME"));

        analyticFrame.attr('id', 'BBAnalyticsIFrame');
        analyticFrame.css({ 'visibility': 'hidden' });

        IFrameDiv.append(analyticFrame);
    }
    
    analyticFrame.attr("src", trackingString);     
}

function nodeIsReallyVisible(node)
{
    if (node.style)
    {
        if (!Sys.UI.DomElement.getVisible(node))
        {
            return false;
        }
        if (node.parentNode)
        {
            return nodeIsReallyVisible(node.parentNode);
        }
    }
    return true;
}


function GetRadioListValue(ctrlID)
{
    var radioctrl = document.getElementById(ctrlID);
    var radio_inputs = radioctrl.getElementsByTagName('INPUT');

    for (var j = 0; j < radio_inputs.length; j++)
    {
        if (radio_inputs[j].checked)
        {
            return radio_inputs[j].value;
        }
    }
}

////////////////////////////////////////
//// This will cover a control with a Div.
//// In order for this div to redraw when it resizes, you need to add
//// the following line in the vb to register the redraw function on the resize event:
//// ScriptManager.RegisterStartupScript(Me, Me.GetType(), "coverElementOnResizeScript", "$addHandler(window, 'resize', coverElementWithDiv_Redraw);", True)
////
//// Also the control to cover should be styled "position: relative" so the child covering div will position correctly.
var coverElementWithDiv_DivArray=[];
function coverElementWithDiv(ctrlId, addCover)
{ 
    var divCover = coverElementWithDiv_DivArray[ctrlId];
    var elementToCover = document.getElementById(ctrlId);
    if (addCover)
    {
        //If the cover doesnt exist, create it
        if (divCover == undefined)
        {            
            divCover = window.top.document.createElement("DIV");
            divCover.style.cssText = "z-index:1000;position:absolute;left:-9px;top:-3px;background-color:gray;filter:alpha(opacity=15);";       
            divCover.style.MozOpacity = 0.15;
            elementToCover.appendChild(divCover);
            coverElementWithDiv_DivArray[ctrlId] = divCover;            
        }
        else
        {
            divCover.style.display='';
        }
        SetDivDimensions(divCover,elementToCover);
    }
    else
    {
        if (divCover !== undefined)
        {
            divCover.style.display = 'none';
        }
    }
};

function SetDivDimensions(div, elementToCover)
{
    div.style.height = Sys.UI.DomElement.getBounds(elementToCover).height + 10 + 'px';
    div.style.width = Sys.UI.DomElement.getBounds(elementToCover).width + 17 + 'px';
}

function coverElementWithDiv_Redraw()
{
    for (var ctrlId in coverElementWithDiv_DivArray)
    {        
        SetDivDimensions(coverElementWithDiv_DivArray[ctrlId],document.getElementById(ctrlId));        
        //Used to force other things being covered to redraw, since they like to disappear
        document.getElementById(ctrlId).style.display='none';
        document.getElementById(ctrlId).style.display='';        
    }
}

function getElementsByClassName(rootElement, className)
{
    var elements = [];
    walkDom(rootElement, function (element) {
        if (element.className && (" " + element.className + " ").indexOf(className, 0) >= 0)
        {
            elements.push(element);
        }
    });
    return elements;
}

function changeCursor(state)
{
	 document.body.style.cursor = state;
}

BLACKBAUD.netcommunity.left = function (str, n)
{
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0,n);
}

BLACKBAUD.netcommunity.right = function (str, n)
{
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

BLACKBAUD.netcommunity.getDateTime = function ()
{
    var right = BLACKBAUD.netcommunity.right;
    var d = new Date();
    var year   = d.getYear();
    var month  = right('0' + (d.getMonth() + 1), 2);
    var day    = right('0' + d.getDate(), 2);
    var hour   = right('0' + d.getHours(), 2);
    var minute = right('0' + d.getMinutes(), 2);
    var second = right('0' + d.getSeconds(), 2);
    if(year < 2000)
    {
        year += 1900;
    }
    return year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second;
}

BLACKBAUD.netcommunity.setBrowserDateTimeForServer = function (controlId)
{
    var hidBrowserDateTime = $get(controlId);
    if (hidBrowserDateTime)
    {
        hidBrowserDateTime.value = BLACKBAUD.netcommunity.getDateTime();
    }
}

BLACKBAUD.netcommunity.consoleLog = function (stuff)
{
    if (typeof(console) !== 'undefined' && console.log)
    {
        console.log(stuff);
    }
};

// Useful in Infragistics event handlers so that the error is not ignored
BLACKBAUD.netcommunity.debuggerMaybe = function ()
{
    if (DebugMode)
    {
        debugger;
    }
};

BLACKBAUD.netcommunity.scrollIntoView = function (id)
{
    var ctrl = $get(id);
    if (ctrl && ctrl.scrollIntoView)
    {
        ctrl.scrollIntoView();
    };
};


////////////////////////////////////////////
// End of script
if (typeof(Sys) !== 'undefined')
{
    Sys.Application.notifyScriptLoaded();
}
////////////////////////////////////////////
// Do not add any code below this
////////////////////////////////////////////
