//=============================================================================
//
//  Core.js
//		This file contains JavaScript functions to handle the core common  
//		client-side functions 
//
//=============================================================================
var UNDEF='undefined';
var mdlprms='resizable:yes;scroll:yes;status:no;center:yes;help:no;dialogWidth:790px;dialogHeight:550px;maximize:yes;';
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')
}

function popupURL(sURL){
    window.open(sURL,'_blank')
}

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 unCheckOtherDGRadios(radio){
	var otherRadios=radio.parentElement.parentElement.parentElement.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;}
	}
}

var modallvl;
//object used to call showModalDialog to show a usercontrol modally
function ModalDialogBB(sCtl, sWidth, sHeight, sQSdata, bResizable, bAllowMaximize){
	//sCtl is the user control to load - use the ~/path syntax
	//sWidth/sHeight should be string and include units eg. '400px'
	//sQSdata is a string and is passed as-is on the query string and handed to your ctl's IBBDialog.data property
	//the clientArgs object will be passed to the client side JS code of the control and can be used for any arguments you like
	this.ctl=sCtl
	this.width=sWidth
	this.height=sHeight
	this.clientArgs=new Object()
	this.qsdata=sQSdata
	this.features="scroll:no;status:no;"
	this.Show = Show
	this.getFeatureString = getFeatureString	
	if(typeof(modallvl)==UNDEF||modallvl<=0){modallvl=0;};
	if(typeof(bResizable)==UNDEF||bResizable){this.resizable='yes'}else{this.resizable='no';}
	if(typeof(bAllowMaximize)==UNDEF||!bAllowMaximize){this.maximize='no'}else{this.maximize='yes';}
			
	function getFeatureString(){return "center:yes;"+this.features+"help:no;dialogWidth:"+this.width+";dialogHeight:"+this.height+";resizable:"+this.resizable+";maximize:"+this.maximize}

	function Show(){
		if(typeof(this.ctl)==UNDEF)	  {alert("showModalDialogBB assert: ctl parameter not set in arg object")}
		if(typeof(this.width)==UNDEF) {alert("showModalDialogBB assert: width parameter not set in arg object")}
		if(typeof(this.height)==UNDEF){alert("showModalDialogBB assert: height parameter not set in arg object")}
		modallvl++;
	
		var AdminURLBase = "AdminPage.aspx"

		//if the modal request for the adminpage comes from an aspx page 
		//not in the app root (e.g. cutesoft javascript) - the path to adminpage will be wrong 
		//strip it down to the root location
		var sLocURL = document.location.href
		var iPos = sLocURL.indexOf('CuteSoft')
		if (iPos != -1) {
			AdminURLBase=sLocURL.substring(0,iPos) + AdminURLBase
		}

		var sURL=AdminURLBase + "?edit=3&md="+modallvl+"&ctl="+this.ctl+"&data="+this.qsdata;
		var ret=window.showModalDialog(sURL, this.clientArgs, this.getFeatureString());
		modallvl--;
		return ret;
	}
}

function PopUpDialogBB(sCtl, sName, sFeatures, sQSdata, bHideCss){
	//sCtl 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
	//sQSdata 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=sCtl
	this.name=sName
	this.features=sFeatures
	this.qsdata=sQSdata
	this.Show = Show
	this.HideCss = bHideCss
		
	function Show(){
		if(typeof(this.ctl)==UNDEF)	  {alert("PopUpDialogBB assert: ctl parameter not set in arg object")}
		var sURL="PopUp.aspx?ctl="+this.ctl+"&data="+this.qsdata+"&hidecss="+this.HideCss;
		var popwin =window.open(sURL,this.name,this.features);
		if( typeof(popwin) != "undefined" && popwin )
		{
			popwin.focus();
		}
	}
}

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	
	
}

function showHideOptionMenu(buttonID,menuID) {
	var oel=getElement(menuID);
	if (oel){
		if(oel.style.display=='none'){
			getElement(buttonID).title="Click here to close this window";
			oel.style.width=document.body.clientWidth/2;
			fadeElementIn(oel,0.5);			
		}else{
			getElement(buttonID).title="Click here to edit and manage your Blackbaud NetCommunity";
			oel.style.display='none';
		}
	}
}

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 {
        window.event.cancelBubble=true
    } 
    catch(e){
    }
    return false;
}

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 ShowModalDialogRedirectVerb(URL, PostbackJS, OnCompleteFunction, windowParams) {

    var ret
    if (arguments.length > 3) {
        ret = window.showModalDialog(URL,'',windowParams);
    } else {
        ret = window.showModalDialog(URL,'',mdlprms);
    }

    var cmd = ''
    
    var bPostback =false
    var bHaveCallback = false    
    
    if (OnCompleteFunction == null){
        OnCompleteFunction = 'DefaultOnModalComplete'
    } else{
        if (OnCompleteFunction.length ==0) {
            OnCompleteFunction = 'DefaultOnModalComplete'
        }
    }

    if (typeof(ret) == 'undefined') {
        cmd="CANCEL"
    }else{
        if (typeof(ret.CMD) == 'undefined') {
            // modal did not set the eventArgument - default to cancel
            // contentcontrols should pass this down via the AddDialogCloseScript call
            cmd="CANCEL"
        }else {
            if (ret.CMD == "") {
                cmd="CANCEL"
            } else {
                cmd = ret.CMD
            }
        }
    }
    

    var f = ' ' + OnCompleteFunction + "(\"" + cmd + "\",\"" + PostbackJS + "\")"

    eval(f)
}

function DefaultOnModalComplete(CMD, PostbackJS) {

    //alert('Cmd is ' + CMD)
    //default behavior - in 4.1 was to postback for no reason - no matter what happened in the modal
    //however I'm changing that - postbacks in the caller will only happen now if a MODAL SAVE 
    //verb fired in the modal
    //Note that it is up to the modal control to provide the CMD via the AddDialogCloseScript - 4.1 and older
    //code did not do this and so all are being treated as CANCEL (which in the old days still round tripped you)
    
    // create your own OnComplete function if you don't want the default. You specify the name of 
    // that function when you create the ModalDialogRedirect verb.

    if (CMD == 'SAVE' || CMD == 'NEXT') {
        eval(PostbackJS)
    }
}

function AddBorderToPaddedElement(elt, borderStyle, paddingWithBorder) {
    elt.style.border = borderStyle
    elt.style.padding = paddingWithBorder
}

function RemoveBorderFromPaddedElement(elt, paddingWithoutBorder) {
    elt.style.border = ''
    elt.style.padding = paddingWithoutBorder
}
