/*This file contains generic javascript functions that could be used on any page*/

function gebid(what)
{
	//good ol' getElementById
	return document.getElementById(what)
}

function showhide(what,num)
{
    //what=object
    //num: 1=show, 0=hide
 
    if(gebid(what))
    {
        if(num==1)
        {
            gebid(what).style.visibility='visible'
        }
        else if(num==0)
        {
            gebid(what).style.visibility='hidden'
        }
    }
}

function showhideonclick(what)
{
    if(getstyle(what,'visibility')=='visible')
    {
        gebid(what).style.visibility='hidden'
    }
    else
    {
        gebid(what).style.visibility='visible'
    }
}

function changedisplay(idx,dis)
{
	//senddebugmsg('idx='+idx+'<br>dis='+dis)
	//alert('dis='+dis+'\nieverx()<8='+(ieverx()<8)+'\n(ieverx()!=false)='+(ieverx()!=false))
	if(gebid(idx))
	{
		if(((dis=='table') && (ieverx()<8) && (ieverx()!=false))) //(isie()) && 
		{
			gebid(idx).style.display='block'	
		}
		else
		{
			gebid(idx).style.display=dis
		}
	}
}

function showhidebox(idx,vis,disp)
{
	//vis=visibility: show or hide
	//disp=display: block or none
	if(vis==1)
	{
		gebid(idx).style.visibility='visible'
	}
	else if(vis==0)
	{
		gebid(idx).style.visibility='hidden'
	}
	
	if(disp==1)
	{
		gebid(idx).style.display='block'
	}
	else if(disp==0)
	{
		gebid(idx).style.display='none'
	}
}

function toggleshowhidebox(idx)
{
	var el=gebid(idx)
	var elvis=getstyle(idx,'visibility') //element visibility
	var eldis=getstyle(idx,'display') //element visibility

	if((elvis=='hidden') || (eldis=='none'))
	{
		gebid(idx).style.visibility='visible'
		gebid(idx).style.display='block'
	}
	else
	{
		gebid(idx).style.visibility='hidden'
		gebid(idx).style.display='none'
	}
}


function switchboxes(idx,num,img)
{
	/*
	handles a series of tabs with associated header images-
	switches to the selected tab and the tab header image
	*/
	/*
		example: switchboxes('artists',0,'homepageTab');
		
		tabs should be named:
		tabname_1
		tabname_2
		etc.
		
		images should be named:
		image_on.*
		image_off.*
	*/
	ct=0
	do
	{
		if(ct==num)
		{
			changedisplay(idx+'_'+ct,'block')
			if(gebid(img+'_'+ct))
			{
				//getpath(gebid(img+'_'+ct).src)
				//getextension(gebid(img+'_'+ct).src)
				gebid(img+'_'+ct).src=getpath(gebid(img+'_'+ct).src)+'/'+img+'_'+ct+'_on.'+getfileext(gebid(img+'_'+ct).src)[1]
			}
		}
		else
		{
			changedisplay(idx+'_'+ct,'none')
			if(gebid(img+'_'+ct))
			{
				gebid(img+'_'+ct).src=getpath(gebid(img+'_'+ct).src)+'/'+img+'_'+ct+'_off.'+getfileext(gebid(img+'_'+ct).src)[1]
			}
		}
		ct++
	}while(gebid(idx+'_'+ct))
}

function getpath(pth)
{
	/*receives a path, splits up the folders, deletes the file (the pop()) and returns only the path without the filename.
	example: 
		receives:
			/images/specialsections/rtr2010/header_artists.jpg
		returns:
			/images/specialsections/rtr2010/
	*/
	ptharr=pth.split('/')
	ptharr.pop()
	newpath=ptharr.join('/')
	return newpath
}

function getfileext(pth)
{
	/*returns a 2D array with the filename and extension
	example:
		receives:
			/images/specialsections/rtr2010/header_artists.jpg
		returns:
			['header_artists','jpg']
	*/
	ptharr=pth.split('/')
	fullfn=ptharr[ptharr.length-1].split('.')
	return fullfn
}

function toggleimg(idx)
{
	/*
	toggles between two images (like for mouseover/out events
	images must be named with this pattern:
	originalimg_off
	originalimg_over
	
	idx is an id of an <img>
	
	example: onmouseover="toggleimg(this.id)"
	*/
	s=gebid(idx).src
	newfn=''
	if(/\_over$/i.test(getfileext(s)[0]))
	{
		//turn off
		newfn=getfileext(s)[0].replace(/\_over$/gi,'_off.')
	}
	else if(/\_off$/i.test(getfileext(s)[0]))
	{
		newfn=getfileext(s)[0].replace(/\_off$/gi,'_over.')
	}
	
	if(newfn!='')
	{
		gebid(idx).src=getpath(s)+'/'+newfn+getfileext(s)[1]
	}
	else
	{
		return false
	}
}

function isie()
{
	if(navigator.appName=='Microsoft Internet Explorer')
	{
		return true;
	}
	else
	{
		return false;
	}
}

function ieverx()
{
	/*
		Returns the version of ie, or false if not ie
	*/
	if(isie())
	{
		iever=/MSIE (\d+\.\d+);/.exec(navigator.userAgent)
		return parseInt(iever[1]);
	}
	else
	{
		return false;
	}
}

function getstyle(idx,styleelement)
{
	//styleelement should always be formatted in w3c xxx-yyy format (ex: 'padding-top', 'height', 'list-style-type', etc.)
	//alert('document.getElementById(idx).currentStyle.'+formatCSStag(styleelement,1))
	//alert(gebid(idx).currentStyle.height)
	if(navigator.appName=='Microsoft Internet Explorer')
	{
		return eval('document.getElementById(idx).currentStyle.'+formatCSStag(styleelement,1))
	}
	else
	{
		return window.getComputedStyle(document.getElementById(idx), "").getPropertyValue(styleelement)
	}
}


function swapsrc(ob,swpimg)
{
	//generic image swap function
	gebid(ob).src=swpimg
}

function tog(idx)
{
	Effect.toggle(idx, 'slide', { duration: .5 });
}

function curTime()
{
	//returns the current time in xx:xx:xx format
	var curdate=new Date()
	var hours = curdate.getHours()
	var minutes = curdate.getMinutes()
	var seconds = curdate.getSeconds()
	if(hours<10)
	{
		hours='0'+hours
	}
	if(minutes<10)
	{
		minutes='0'+minutes
	}
	if(seconds<10)
	{
		seconds='0'+seconds
	}
	return hours+':'+minutes+':'+seconds
}


function addimgtitles()
{
	/*
		copies alt tags to title tags on all images on the page
	*/
	for(var x=0;x<document.images.length;x++)
	{
		document.images[x].title=document.images[x].alt
	}
}


function showpopup(idx)
{
	//adds a background mask, changes the display of an absolutely-positioned div to be visible, and centers it
	createmask()
	changedisplay(idx,'table')
	centerelement(idx)
}

function hidepopup(idx)
{
	/*
		removes the page mask (if present) and then changes the display of the popup to none
		usually used on pages that have a popup defined in the HTML on the page, not one dynamically inserted, but could be used on a dynamic one
	*/
	if(gebid('bgeapagemask'))
	{
		removebox('bgeapagemask')
	}
	
	if(gebid(idx))
	{
		changedisplay(idx,'none')
	}
}

function getqsval(idx)
{
	//returns a querystring value if found
	/*
		example:
		page=http://www.example.com/default.asp?myvar1=yay&myvar2=&myvar3=blah
		getqsval('myvar1') returns 'yay'
		getqsval('myvar2') returns ''
		getqsval('myvar3') returns 'blah'
		
		if there is no querystring, returns false
	*/
	var retval=''
	if(location.search=='')
	{
		return retval
	}
	origqs=location.search.substr(1) //strip out the ?
	origqs=origqs.replace(/&amp;/g,'&')
	qs=origqs.split('&')
	
	for(var x=0;x<qs.length;x++)
	{
		curel=qs[x].split('=')
		if(curel[0]==idx)
		{
			retval=unescape(curel[1])
			break;
		}
	}
	return retval
}

function getcookie(idx)
{
	/*
		returns a cookie value if found
		returns false if there are no cookies
	*/
	var retval=''
	if(document.cookie=='')
	{
		return retval
	}
	
	cookies=document.cookie.split('; ')
	
	for(var x=0;x<cookies.length;x++)
	{
		curel=cookies[x].split('=')
		if(curel[0]==idx)
		{
			retval=curel[1]
			break;
		}
	}
	return retval
}

/*=================================================================================================*/
/*start*/
/*debugbox functions*/
/*=================================================================================================*/

function dbjskp(e)
{
	//determines which key is pressed
		var kp
		if(navigator.appName.indexOf("Microsoft") > -1)
		{
			kp=window.event.keyCode
		}
		else
		{
			kp=e.which
			//alert(kp)
		}
		
		
		if ((window.event || e) && kp == 13)
		{
			senddebugmsg(gebid('dbjsformtxt').value+':<br>'+eval(gebid('dbjsformtxt').value))
/*
			if(eval(myform.dbjsformtxt.value))
			{
				senddebugmsg(eval(myform.dbjsformtxt.value))
			}
			else
			{
				sendde
			}*/
		}
		else
		{
			return true;
		}

}

function senddebugmsg(txt)
{
	if(!gebid('dbjsformtxt'))
	{
		createdebugbox()
	}
	gebid('output').innerHTML=curTime()+'<br>'+txt+'<br><br>'+gebid('output').innerHTML
}

function showhidedebugbox()
{
	if(gebid('debugboxoc').innerHTML=='Hide')
	{
	   gebid('outputwrapper').style.width='15px';
	   gebid('outputwrapper').style.padding='0px'
	   gebid('outputwrapper').style.overflow='hidden'
	   gebid('debugboxoc').innerHTML='<b><</b>'
	}
	else
	{
	   gebid('outputwrapper').style.width='300px';
	   gebid('outputwrapper').style.padding='10px'
	   gebid('outputwrapper').style.overflow='auto'
	   gebid('debugboxoc').innerHTML='Hide'
	}
}

function removedebugbox()
{
	removebox('outputwrapper')
}

function createdebugbox()
{
	var x=document.createElement('div')
	x.setAttribute('id','debugboxwrapper')
	
	var ih=''
	ih+='<div style="position:fixed;width:300px;height:85%;overflow:auto;right:0px;top:50px;padding:10px;border:1px solid red;font-size:11px;font-family:\'Courier New\', Courier, monospace;background-color:#ffffff;z-index:65000;" id="outputwrapper">'
	ih+='<div style="height:26px;overflow:hidden;width:300px;">'
	ih+='<div style="position:relative;cursor:pointer;width:auto;background-color:red;padding:5px;float:left;" onclick="showhidedebugbox()" id="debugboxoc">Hide</div>'
	ih+='<div style="position:relative;cursor:pointer;width:100px;background-color:red;padding:5px;float:left;margin-left:10px;" onclick="gebid(\'output\').innerHTML=\'\'">Clear output</div>'
	ih+='<div style="position:relative;cursor:pointer;width:auto;background-color:red;padding:5px;float:left;margin-left:10px;" onclick="removedebugbox()">Remove</div>'
	ih+='</div>'
	ih+='<div style="width:300px;height:26px;overflow:hidden;" id="dbjseval">'
	ih+='<input type="text" name="dbjsformtxt" id="dbjsformtxt" style="width:280px;" onkeypress="dbjskp(event)">'
	ih+='</div>'
	ih+='<div style="position:relative;background-color:#ffffff;" id="output">&nbsp;</div>'
	ih+='</div>'

	x.innerHTML=ih
	document.body.appendChild(x)
}

/*=================================================================================================*/
/*end*/
/*debugbox functions*/
/*=================================================================================================*/


function removebox(idx)
{
	if(gebid(idx))
	{
		var toremove=gebid(idx)
		var parent=toremove.parentNode
		parent.removeChild(toremove)
	}
}


function makesameheight(idx1,idx2)
{
	//makes 2 divs the same height. ie requires using the clientHeight and subtracting the top & bottom padding
	
	
	//senddebugmsg('idx1.padding='+getstyle(idx1,'paddingBottom'))
	if(gebid(idx1) && gebid(idx2))
	{
		if(isie()==false)
		{
			if(gebid(idx1).clientHeight > gebid(idx2).clientHeight)
			{
				gebid(idx2).style.height=parseFloat(getstyle(idx1,'height'))+'px'
			}
			else
			{
				gebid(idx1).style.height=parseFloat(getstyle(idx2,'height'))+'px'
			}
		}
		else
		{
			if(gebid(idx1).clientHeight > gebid(idx2).clientHeight)
			{
				gebid(idx2).style.height=gebid(idx1).clientHeight-parseFloat(getstyle(idx1,'paddingBottom'))-parseFloat(getstyle(idx1,'paddingTop'))+'px'
			}
			else
			{
				gebid(idx1).style.height=gebid(idx2).clientHeight-parseFloat(getstyle(idx2,'paddingBottom'))-parseFloat(getstyle(idx2,'paddingTop'))+'px'
			}
		}
	}
}

function makesameheightmulti(arr)
{
	//takes a ~-separated list of id's then finds the largest one and makes them all the height of the largest one
	//format of arr: idx1~idx2~idx3~idx4
	//no trailing ~
	
	var maxheight=0
	var curheight=0
	idxarr=arr.split('~')
	hflg=false
	
	//loop and find the tallest element
	for(var x=0;x<idxarr.length;x++)
	{
		if(gebid(idxarr[x]))
		{
			curheight=gebid(idxarr[x]).clientHeight
		}
		if(curheight>maxheight)
		{
			maxheight=curheight
			hflg=true
		}
	}
	
	if(hflg==true)
	{
		//set all elements' height to the maxheight
		for(var x=0;x<idxarr.length;x++)
		{
			if(gebid(idxarr[x]))
			{
				gebid(idxarr[x]).style.height=maxheight+'px'
			}
		}
	}
}

function formatCSStag(txt,typex)
{
	//changes a tag from the xxx-yyy to xxxYyy format or xxxYyy to xxx-yyy
	//W3C uses xxx-yyy for getComputedStyle
	//ie uses xxxYyy
	var str
	var newstr=''
	if(typex==1)
	{
		//example: padding-top to paddingTop
		str=txt.split('-')
		newstr=str[0]
		for(var q=1;q<str.length;q++)
		{
			newstr+=str[q].charAt(0).toUpperCase()+str[q].substr(1,str[q].length)
		}
		
	}
	else if(typex==2)
	{
		//example: paddingTop to padding-top
		var cap=0
		str=txt
		var flg=false
		var xleft='',xright=''
		do
		{
			cap=str.search(/[A-Z]/)
			if(cap>-1)
			{
				//current letter is a capital letter
				xleft=str.substring(0,cap)
				xright=str.substring(cap,str.length)
				str=xleft+'-'+xright.charAt(0).toLowerCase()+xright.substr(1,xright.length)
			}
			else
			{
				flg=true
			}
			
		}
		while(flg==false)
		
		newstr=str
	}
	
	return newstr
}

function entsub(myform,evt,js)
{
	//checks to see if the user pressed the enter key in a form field
	
	/*
	example: onkeyup="return entsub(document.myform,event,'VF_myform')"
	myform=form that called this function
	evt=key event
	js=javascript to execute if they pressed enter - useful to call form validation, etc.
	if js is empty, it will immediately submit the form
	*/


	//alert(window.event.keyCode)
	var kp
	if(navigator.appName.indexOf("Microsoft") > -1)
	{
		kp=window.event.keyCode
	}
	else
	{
		kp=evt.which
		//alert(kp)
	}
	
	
	if ((window.event || evt) && kp == 13)
	{
		//enter was pressed
		if(js!='')
		{
			eval(js)
		}
		else
		{
			myform.submit();
		}
	}
	else
	{
		return true;
	}
}

function flipnfill(arrx,tox,preselind,preselval,showSelectOne)
{
	/*
	this function receives an array and a select object
	it adds the items in the array to the select
	arrx=any 2-dimensional array. 
	[0]=the text
	[1]=the value
	
	tox=the select that will receive the array in this format:
	document.form1.<select name>

	preselind=preselected index - if found, it will preselect this
	preselval=preselected value - if found, it will preselect this
	
	showSelectOne=flag - if true, "Select One" will be added as the first item
	*/

	//Clear out the old options
	for(var j=tox.length;j>=0;j--)
	{
		tox[j]=null
	}

	if(showSelectOne==true)
	{
		tox[0]=new Option('Select One:','',false,false)
	}
	//add new options
	for(var i=0;i<eval(arrx).length;i++)
	{
		//syntax for the option object: new Option(text, value, defaultSelected, selected)
		if(((preselind!='')||(preselval!='')) && ((i===preselind)||(preselval==eval(arrx)[i][1])))
		{
			tox[tox.length]=new Option(eval(arrx)[i][0],eval(arrx)[i][1],true,true)
		}
		else
		{
			tox[tox.length]=new Option(eval(arrx)[i][0],eval(arrx)[i][1],false,false)
		}
		
	}

	if(tox.length==0)
	{
		tox[0]=new Option('Please select','')
	}
}

function validateelement(idx,formname,typ)
{
	//this makes sure at least one radio button or select option is selected
	//example: validateelement('VIC_State','<%=strformname%>','select-one')
	var theForm = 'document.'+formname
	var tmpflg=false
	var formElement=eval(theForm)[idx]
	var testval=''

	for (var x=0;x<formElement.length;x++)
	{
		//eval('document.registrationForm.'+idx+'[1].checked')
		if(typ=='select-one')
		{
			//select element
			if(formElement.options[x].selected==true)
			{
				//something was selected
				testval=formElement.options[x].text
			}
			else
			{
				testval=''
			}
		}
		else if(typ=='radio')
		{
			//radio button
			if (formElement[x].checked == true)
			{
				//something was selected
				testval=formElement[x].value
			}
			else
			{
				testval=''
			}
		}
		if(testval != '')
		{
			//make sure the value is not Select One or a separator
			if((testval.toLowerCase().indexOf('select one')==-1) && (testval.toLowerCase().indexOf('----')==-1) && (testval != ''))
			{
				//if it's not select one, not a divider, and not empty, a valid selection was made
				tmpflg=true;
				break;
			}
		}
	}

	return tmpflg
}

function setformerror(idx,xtyp)
{
	/*
		xtyp values:
		1: set error state
		2: remove error state
		
		siv="ScrollIntoView" - holds the first error field to scroll to
	*/
	
	if(xtyp==1)
	{
		gebid('title'+idx).className='formerror'
		formerrflg=true
		
		siv=idx
	}
	else if(xtyp==0)
	{
		gebid('title'+idx).className=''
	}
}


function groupcheckbox(theForm,idx,require)
{
	/*
	loops through a checkbox group (example: VIC_Question_00178group) and creates a ~-delimited list that is set to the value of the associated form element (example: VIC_Question_00178) 
	
	require is a boolean:
	true=user must select at least 1 option
	false=user may leave all options unchecked
	*/
	if((require==null) || (require==undefined))
	{
		require=false
	}
	var grpflg=false
	var grpopts=''
	var mygrp=eval('theForm.'+idx+'group')
	for(var y=0;y<mygrp.length;y++)
	{
		if(mygrp[y].checked)
		{
			//at least 1 option was selected
			grpflg=true
			grpopts+=mygrp[y].value+'~'
		}
	}
	grpopts=grpopts.substr(0,grpopts.length-1)
	if((grpflg==false) && (require==true))
	{
		//no options selected
		setformerror(idx,1)
	}
	else
	{
		setformerror(idx,0)
		gebid(idx).value=grpopts
	}
	return grpflg
}

function getradiobutton(idx,formname)
{
	/*
	returns 1-D array where:
	1st element is the index of which radio button is selected
	2nd element is the value of that radio button
	*/
	var theForm = 'document.'+formname
	var formElement=eval(theForm)[idx]
	var retval=false
	if(formElement[0].type=='radio')
	{
		for (var x=0;x<formElement.length;x++)
		{
			if (formElement[x].checked == true)
			{
				retval=[x,formElement[x].value]
				break;
			}		
		}
	}
	return retval
}

function roundupcheckboxes(inidx,outidx)
{
	//creates a ~-delimited string of checked items and sets the value of outidx to this string
	var inboxid=eval('document.form1.'+inidx)
	var mystr=''
	for(var x=0;x<inboxid.length;x++)
	{
		if(inboxid[x].checked)
		{
			mystr+=inboxid[x].value
			if(x<inboxid.length-1)
			{
				mystr+='~'
			}
		}
	}
	gebid(outidx).value=mystr
}

function setselect(selname,val)
{
	//sets a select to the value in val
	retval=-1
	for(var x=0;x<gebid(selname).length;x++)
	{
		if(gebid(selname).options[x].value==val)
		{
			gebid(selname).selectedIndex=x
			retval=x
			break;
		}
	}
	return x
}

function setcheckboxval(idx,myarr)
{
	/*
	receives an array and sets the value attribute of a checkbox to the first value if checked, or the 2nd value if unchecked.
	example:
	setcheckboxval('mydiv',['yes','no'])
	*/
	if(gebid(idx).checked)
	{
		gebid(idx).value=myarr[0]
	}
	else
	{
		gebid(idx).value=myarr[1]
	}
}

function showcharcnt(idx,tar,max,msg)
{
	gebid(tar).innerHTML=gebid(idx).value.length+'/'+max+' '+msg
}

/*=============================================================================================*/

function isvisible(idx)
{
	var xdisp=getstyle(idx,'display')
	//alert(idx+' '+xdisp)
	if((xdisp=='') || (xdisp==null) || (xdisp=='none'))
	{
		return false
	}
	else
	{
		return true
	}
}


function redirectpage(selectname,targetpage)
{
	//this function will move the browser to the selected page and pass a variable
	//usually used with pages that have a <select>
	//alert(selectname+'\n'+targetpage)
	var st=gebid(selectname).options[gebid(selectname).selectedIndex].text
	window.location=targetpage+'?st='+escape(st)
}

function createmask()
{
	if(!((navigator.appName=='Microsoft Internet Explorer') && (navigator.appVersion.indexOf('MSIE 6.0')>0)))
	{
		//NOT ie6
		var newpagemask=document.createElement("div")
		
		newpagemask.setAttribute("id", "bgeapagemask")
		newpagemask.setAttribute("class", "bgeapagemask")
		
		document.body.insertBefore(newpagemask, document.body.firstChild)
		gebid('bgeapagemask').className='bgeapagemask'
	}

}

function centerelement(idx)
{
	if(gebid(idx).style.position!='fixed')
	{
		gebid(idx).style.position='fixed'
	}
	//alert(gebid(idx).clientWidth)
	gebid(idx).style.left="50%"
	gebid(idx).style.marginLeft='-'+(gebid(idx).clientWidth/2)+'px'
	gebid(idx).style.top="50%"
	var ht
	//alert(getstyle(idx,'height'))
	if(isNaN(parseFloat(getstyle(idx,'height'))))
	{
		ht=gebid(idx).clientHeight
	}
	else
	{
		ht=gebid(idx).clientHeight
		//ht=parseFloat(getstyle(idx,'height'))
	}
	var mt='-'+(ht/2)+'px'
	gebid(idx).style.marginTop=mt
	
}

function vertcenter(idx)
{
	/*
		Vertically centers a box
		To vertically center, the box must have a height defined, and set the top to 50% and the marginTop to negative 1/2 the height.
		Also, it must have position:absolute and its containing box (parent) must have position:absolute or relative. 
		This checks to see if the parent has position:relative or absolute and if not it sets the position to relative.
	*/

	gebid(idx).style.height=gebid(idx).clientHeight+'px'
	gebid(idx).style.top='50%'
	gebid(idx).style.position='absolute'
	gebid(idx).style.marginTop='-'+(gebid(idx).clientHeight/2)+'px'
	
	if((gebid(idx).parentNode.style.position !='relative') && (gebid(idx).parentNode.style.position !='absolute'))
	{
		gebid(idx).parentNode.style.position='relative'
	}
}

function setieopacity(idx,val)
{
	gebid(idx).style.filter='alpha(opacity='+val+')'	
}

function appendscript(url)
{
	var e = document.createElement("script");
	e.src = url;
	e.type="text/javascript";
	document.getElementsByTagName("head")[0].appendChild(e);
}


function getajaxhtml(pth,qs,js)
{
	createRequest()
	
	var url=pth
	if((qs==null) || (qs==undefined))
	{
		qs=''
	}
	//qs=qs.replace(/\'/gi,'&#39;')
	//qs=qs.replace(/\"/gi,'&#34;')
	var sel=escape(qs)
	request.open("POST",url,true)

	request.onreadystatechange = function (){xajaxshow(js)}
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
	request.send(sel)
}

function xajaxshow(js)
{
	if(request.readyState==4)
	{
		var resp=request.responseText
		//alert(resp)
		if(resp=='')
		{
			alert('An error has occurred.')
		}
		else
		{
			resp=unescape(resp)
		}
		//alert(resp)
		if (request.status==200)
		{
			ajaxhtmldiv=document.createElement('div')
			newid='ajaxpopup_'+new Date().getTime()
			ajaxhtmldiv.setAttribute('id',newid)
			ajaxhtmldiv.className='stdpopup'

			newih=''
			//insert close button
			newih+='<div style="position:absolute;right:15px;top:15px;height:16px;color:#cacaca;font-weight:bold;font-size:13px;cursor:pointer;" id="" onclick="removebox(\'bgeapagemask\');removebox(\''+newid+'\')">\n'
			newih+='\tCLOSE <img src="/assets/images/buttons/GreyXButton.gif" style="margin-left:5px;vertical-align:text-top;">\n'
			newih+='</div>\n\n'
			
			newih+=resp
			
			ajaxhtmldiv.innerHTML=newih
			
			createmask()
			document.body.insertBefore(ajaxhtmldiv,document.body.firstChild)
			centerelement(newid)
			//showpopup(ajaxhtmldiv)
			
			eval(js)
		}
		else
		{
			alert("An error has occurred. The server said: "+request.status)
			//document.getElementById('files').innerHTML=resp.replace(/\+/g,' ') //'<span style="color:#FF0000">An error occurred</span>'
		}
	}
}


function openetf()
{
	/*opens the email to friend box*/
	getajaxhtml('/includes/toolbox/popupETF.asp','','openetfproc()')

}

function openetfproc()
{
	/*
		js that executes after the email to friend box opens
	*/

	//var tmp=gebid('toolboxemailtofriend').onkeyup
	//gebid('toolboxemailtofriend').onkeyup=null
	gebid('VIC_Question_00026').focus();
	//gebid('toolboxemailtofriend').onkeyup=tmp
	
	gebid('VIC_Question_00421').value=window.location;
	
}

//get twitter
var twits=3
var whichtwit=''
function getTwitter(which)
{
	createRequest()
	var sel=''
	var url='/globalassets/includes/gettwitter.asp'
	sel+='twits='+twits
	sel+='&feed='+which
	
	
	request.open("POST",url,true)

	whichtwit=which
	request.onreadystatechange = updatetwitter
	request.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
	request.send(sel)
}
var XMLdoc
var twarr= []
function updatetwitter()
{
	if(request.readyState==4)
	{

		//alert(request.responseText)
		if (request.status==200)
		{
			//var resp=request.responseText
			//alert(request.responseText)
			//parse response
			XMLdoc=request.responseXML
			var twarr= []
			var curdate=''
			var curtxt=''
			
			var stats=XMLdoc.getElementsByTagName('status')
			for(var x=0;x<twits;x++)
			{
				curdate=stats[x].getElementsByTagName('created_at')[0].firstChild.nodeValue
				curtxt=stats[x].getElementsByTagName('text')[0].firstChild.nodeValue
				curtxt=curtxt.replace(/\'/g,'&rsquo;')

				twarr.push(eval('[\''+curdate+'\',\''+curtxt+'\']'))
			}

			var twit=''
			for(var x=0;x<twits;x++)
			{
				curdate=twarr[x][0].split(' ')
				//fix time
				var curtime=curdate[3].split(':')
				var newtime
				if(curtime[0]<=12)
				{
					if(curtime[0]=='00')
					{
						newtime='12:'+curtime[1]
					}
					else
					{
						newtime=curtime[0]+':'+curtime[1]
					}
					newtime+=' AM'
				}
				else
				{
					newtime=(parseInt(curtime[0])-12)+':'+curtime[1]+' PM'
				}
				curdate=curdate[0]+' '+curdate[1]+' '+curdate[2]+' '+newtime
				
				var notopm=''
				if(x==0)
				{
					notopm='margin-top:0px;'
				}
				else
				{
					notopm=''
				}
				twit+='<div style="margin-bottom:10px;'+notopm+'"><div class="twittime">'+curdate+"</div>"
				curtxt=twarr[x][1]
				var findURL=curtxt.indexOf('http://')
				
				if(findURL > -1)
				{
					//extract the URL
					//find the next space
					var endspace=curtxt.indexOf(' ',findURL)
					if(endspace==-1)
					{
						endspace=curtxt.length
					}

					var curURL=curtxt.substring(findURL,endspace)
					//alert(curURL+' '+findURL+' '+endspace)
					//alert('findURL = '+findURL+'\nendspace = '+endspace+'\ncurURL = '+curURL+'\ncurtxt = '+curtxt)
					curtxt=curtxt.substring(0,findURL)+' <a href="'+curURL+'">'+curURL+'</a>'+curtxt.substring(endspace)
					//alert(curtxt)
				}
				twit+='<div class="twittxt">'+curtxt+'</div></div>\n'
			}

			if(whichtwit=='bgeaprayerteam')
			{
				twit+='<div style="margin-top:10px;"><a href="http://twitter.com/bgeaprayerteam">Follow Prayer Team on Twitter &raquo;</a></div>'
			}
			document.getElementById('twitterbox').innerHTML=twit
		}
		else
		{
			//alert("The server said: "+request.status+'\n'+resp)
			document.getElementById('twitterbox').innerHTML='<span style="color:#FF0000">There was an error retrieving the Twitter updates</span>'
		}
	}
}

/*=====================================================================*/
var closeevt=null

function checkclosepop(evt,evaljs,keyx)
{
	/*
		if the user presses esc (keyCode 27) this will remove the listener and then eval the js passed in
		example:
		
		closeevt=function(evt){checkclosepop(evt,'closevidpopup()')}
		window.addEventListener('keypress',closeevt, false)
	*/
	if(!keyx)
	{
		//default to 27 - ESC
		keyx=27
	}
	if(evt.keyCode==keyx)
	{
		if(!isie())
		{
			window.removeEventListener('keydown',closeevt, false)
		}
		else
		{
			document.body.detachEvent('keydown',closeevt)
		}
		eval(evaljs)
	}
}
/*=====================================================================*/

function createGooglemap()
{
	//Google maps keys:

	//get key here: http://code.google.com/apis/maps/signup.html

	//www.billygraham.org: 
	// ABQIAAAA2h_EE9iqtiphNGtRjd6-3BTTcHsd-W4aEQMCYC93ybmgDg5xhBQR0rGZ-nf7gVpvRvusgR-EXNEX1g

	//staging.billygraham.org:
	// ABQIAAAA2h_EE9iqtiphNGtRjd6-3BRRFPVZMz9It76ARiyBve0rKAJqnxQp4UBTdMinaat-eCa6WgRyOsSoKQ

	//10.254.79.167:
	// ABQIAAAA2h_EE9iqtiphNGtRjd6-3BRnv0raeS6aXaWm1zjOr9ZYF6pTZxSpFVWYDwVQkbE5yuPCoqEd5C5mjA

	//dev.grahamfestival.org:
	// ABQIAAAAJuFaicxosR-ecf5ZRJzIZBTHMw6TbP5O7kGSvYJLXybEks6SFBTX2wsVmIq6q_THEF1fnV6aqKG_kA
	
	//staging.grahamfestival.org:
	// ABQIAAAAJuFaicxosR-ecf5ZRJzIZBRIHWMN5Mjw34vmBLVtRd7dq_7DORSTuBn9UZFIbgLFwYFhyYYpV-4A-A
	
	//www.grahamfestival.org
	// ABQIAAAAJuFaicxosR-ecf5ZRJzIZBSZpFK5J_uhj83qRiyhpippOvCAHRRXlARNryQsTELJB9EcsEpAtQq5Ew
	
	//new.grahamfestival.org
	// ABQIAAAAJuFaicxosR-ecf5ZRJzIZBTCMHW-0ezu5kx3tOzjVKfCHYoT_xQ78PlxNvy-3LF5wCVrfnD7mw5oAg
	var h=window.location.host
	var k=null
	
	if (h.indexOf('www.billygraham.org')>-1)
	{
		k='ABQIAAAA2h_EE9iqtiphNGtRjd6-3BTTcHsd-W4aEQMCYC93ybmgDg5xhBQR0rGZ-nf7gVpvRvusgR-EXNEX1g'
	}
	else if(h.indexOf('staging.billygraham.org')>-1)
	{
		k='ABQIAAAA2h_EE9iqtiphNGtRjd6-3BRRFPVZMz9It76ARiyBve0rKAJqnxQp4UBTdMinaat-eCa6WgRyOsSoKQ'
	}
	else if(h.indexOf('10.254.79.167')>-1)
	{
		k='ABQIAAAA2h_EE9iqtiphNGtRjd6-3BRnv0raeS6aXaWm1zjOr9ZYF6pTZxSpFVWYDwVQkbE5yuPCoqEd5C5mjA'
	}
	else if(h.indexOf('dev.grahamfestival.org')>-1)
	{
		k='ABQIAAAAJuFaicxosR-ecf5ZRJzIZBTHMw6TbP5O7kGSvYJLXybEks6SFBTX2wsVmIq6q_THEF1fnV6aqKG_kA'
	}
	else if(h.indexOf('staging.grahamfestival.org')>-1)
	{
		k='ABQIAAAAJuFaicxosR-ecf5ZRJzIZBRIHWMN5Mjw34vmBLVtRd7dq_7DORSTuBn9UZFIbgLFwYFhyYYpV-4A-A'
	}
	else if(h.indexOf('www.grahamfestival.org')>-1)
	{
		k='ABQIAAAAJuFaicxosR-ecf5ZRJzIZBSZpFK5J_uhj83qRiyhpippOvCAHRRXlARNryQsTELJB9EcsEpAtQq5Ew'
	}
	else if(h.indexOf('new.grahamfestival.org')>-1)
	{
		k='ABQIAAAAJuFaicxosR-ecf5ZRJzIZBTCMHW-0ezu5kx3tOzjVKfCHYoT_xQ78PlxNvy-3LF5wCVrfnD7mw5oAg'
	}
	else if(h.indexOf('new.grahamfestivals.org')>-1)
	{
		k='ABQIAAAAJuFaicxosR-ecf5ZRJzIZBTfe_upWJuMaxjH_TyjFn4sxOEBKBSpZ1kMEvC02JzvhFJrm5GmITlJbQ'
	}
	else if(h.indexOf('www.grahamfestivals.org')>-1)
	{
		k='ABQIAAAAJuFaicxosR-ecf5ZRJzIZBTXECA1ZBpdZq_TKblQFE38LreULhSQmxB3QNQDjwQPkib_fifjNG85kw'
	}
	else if(h.indexOf('grahamfestivals.com')>-1)
	{
		k='ABQIAAAAJuFaicxosR-ecf5ZRJzIZBQoDpAVQAIBALoU7li-v6spNAKlxhSAeOrDjUSCaFL2HV64P4FnLIlxiA'
	}
	
			

	return '<script src="http://maps.google.com/maps?file=api&amp;v=2.x&amp;key='+k+'" type="text/javascript"></script>'
}

/*=================================================================================================*/
/*start*/
/*CSS Rule Functions http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript*/
/*=================================================================================================*/

/*
examples:
blah=getCSSRule('.GlobalBarDropDownMenu a:link')
blah.style.color='#ffffff'

blah=getCSSRule('.GlobalBarDropDownMenu a:visited')
blah.style.color='#ffffff'

blah=getCSSRule('.GlobalBarDropDownMenu p')
blah.style.borderBottom='1px solid #ffffff'
*/

function getCSSRule(ruleName, deleteFlag) {               // Return requested style obejct
   ruleName=ruleName.toLowerCase();                       // Convert test string to lower case.
   if (document.styleSheets) {                            // If browser can play with stylesheets
      for (var i=0; i<document.styleSheets.length; i++) { // For each stylesheet
         var styleSheet=document.styleSheets[i];          // Get the current Stylesheet
         var ii=0;                                        // Initialize subCounter.
         var cssRule=false;                               // Initialize cssRule. 
         do {                                             // For each rule in stylesheet
            if (styleSheet.cssRules) {                    // Browser uses cssRules?
				try
				{
					cssRule = styleSheet.cssRules[ii];         // Yes --Mozilla Style
				}
				catch(err)
				{
					cssRule=false;
				}
            } else {                                      // Browser uses rules?
				try
				{
					cssRule = styleSheet.rules[ii];            // Yes IE style. 
				}
				catch(err)
				{
					cssRule=false;
				}
            }                                             // End IE check.
            if (cssRule)  {                               // If we found a rule...
					if((cssRule.type==1) || (isie())){						//if the type is a STYLE_RULE
               if (cssRule.selectorText.toLowerCase()==ruleName) { //  match ruleName?
                  if (deleteFlag=='delete') {             // Yes.  Are we deleteing?
                     if (styleSheet.cssRules) {           // Yes, deleting...
                        styleSheet.deleteRule(ii);        // Delete rule, Moz Style
                     } else {                             // Still deleting.
                        styleSheet.removeRule(ii);        // Delete rule IE style.
                     }                                    // End IE check.
                     return true;                         // return true, class deleted.
                  } else {                                // found and not deleting.
                     return cssRule;                      // return the style object.
                  }                                       // End delete Check
               }                                          // End found rule name
					}												//end STYLE_RULE check
            }                                             // end found cssRule
            ii++;                                         // Increment sub-counter
         } while (cssRule)                                // end While loop
      }                                                   // end For loop
   }                                                      // end styleSheet ability check
   return false;                                          // we found NOTHING!
}                                                         // end getCSSRule 

function killCSSRule(ruleName) {                          // Delete a CSS rule   
   return getCSSRule(ruleName,'delete');                  // just call getCSSRule w/delete flag.
}                                                         // end killCSSRule

function addCSSRule(ruleName) {                           // Create a new css rule
   if (document.styleSheets) {                            // Can browser do styleSheets?
      if (!getCSSRule(ruleName)) {                        // if rule doesn't exist...
         if (document.styleSheets[0].addRule) {           // Browser is IE?
            document.styleSheets[0].addRule(ruleName, null,0);      // Yes, add IE style
         } else {                                         // Browser is IE?
            document.styleSheets[0].insertRule(ruleName+' { }', 0); // Yes, add Moz style.
         }                                                // End browser check
      }                                                   // End already exist check.
   }                                                      // End browser ability check.
   return getCSSRule(ruleName);                           // return rule we just created.
} 
/*=================================================================================================*/
/*end*/
/*CSS Rule Functions http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript*/
/*=================================================================================================*/


/*=================================================================================================*/
/*=================================================================================================*/
/*========================= Experimental! =*/
/*=================================================================================================*/
/*=================================================================================================*/

function DOMlookup(start,lookfor)
{
	//this starts at a point in the DOM and looks up until it finds the lookfor var.
	//if it doesn't find it, returns false
	//else, returns true
	//senddebugmsg(start+'<br>')
	var tarel=gebid(start)
	var flg=false
	do
	{
		if(tarel.parentNode.id==lookfor)
		{
			//found
			flg=true
			break
		}
		else
		{
			flg=false
			tarel=tarel.parentNode
		}
	}while(tarel.parentNode.nodeName!='BODY')

	return flg
}


/*=================================================================================================*/
/*=================================================================================================*/
/*========================= Obsolete/unused! =*/
/*=================================================================================================*/
/*=================================================================================================*/

/*
function crossfade(img,desc,inout)
{
	//document.getElementById('xyz').innerHTML=inout
	if(inout==1)
	{
		//fade image out, description in
		Effect.Fade(document.getElementById(img), { duration: .35,to:.25 })
		Effect.Appear(document.getElementById(desc), { duration: .35,to:1.0 })
	}
	else if(inout==0)
	{
		//fade image in, description out
		Effect.Appear(document.getElementById(img), { duration: .35,to:1.0 })
		Effect.Fade(document.getElementById(desc), { duration: .35,to:0.0 })
	}
}
*/