// JavaScript Document
function ge(str) {
	return document.getElementById(str);
}

function clearAndSubmit() {
	ge('q').value = '';
	ge('frmEventFilter').submit();
}

function checkThisBox(obj) {
	if(obj) {
		if(obj.checked){
			obj.parentNode.className = 'selected';
			} else {
			obj.parentNode.className = '';
		}
	}
}

// disable form
function doDisableForm(f) {
	if(f) {
		for (i=0;i<f.elements.length;i++) {
			f.elements[i].disabled = true;
			f.elements[i].style.background = '#EEE';
		}
	}
}

// formats phone numbers as user types input
// usage: <input onkeypress="formatPhoneNum(this)"
function formatPhoneNum(e) { 
	var PhoneLength;
	PhoneLength = e.value.length;
	// puts in the first dash 
	if (PhoneLength==4 && e.value.substring(2,3) != '-'){
		e.value = e.value.substring(0,3) + '-' + e.value.substring(3,PhoneLength);
	}
	// stepping over where the dash usually goes
	if (PhoneLength==9 && e.value.substring(7,8) != '-'){
		e.value = e.value.substring(0,7) + '-' + e.value.substring(7,PhoneLength);
	}
	// remove double dash
	e.value = e.value.replace('--','-');
}

function cancelModify() {
	try {
		history.go(-1);
	} catch(e) {
		location.href = 'index.cfm';
	}
}

function showHideTimes(obj) {
	var d = '';
	if(obj.checked) {
		d = 'none';
	}
	ge('start_end_times').style.display = d;
}

function showTab(o) {
	var arrTabs = ge('myTabs').getElementsByTagName('a');
	for(var i=0; i < arrTabs.length; i++) {
		arrTabs[i].className = 'tab';
		ge('cat_' + escape(arrTabs[i].innerHTML)).style.display = 'none';
	}
	o.className = 'selected tab';
	ge('cat_' + escape(o.innerHTML)).style.display = 'block';
	o.blur();
}

/*
	calculates the duration of time between two times
	assumes the times are in a pair of 3 select boxes hh : mm tt
	Automatically puts the duration in the duration object as inner HTML
*/
function calcDuration() {
	var h1 = ge('START_HOUR');
	var m1 = ge('START_MINUTE');
	var t1 = ge('START_AMPM');
	var h2 = ge('END_HOUR');
	var m2 = ge('END_MINUTE');
	var t2 = ge('END_AMPM');3
	var d = ge('duration');
	
	// create the date/time objects to hold the times
	var time1 = new Date();
	var time2 = new Date();
	
	// convert hours to 24 hr format
	/*
		Since the values in the hour drop down are 01 - 12, parseInt needs to have a radix of 10
		# If the string begins with "0", the radix is 8 (octal). This feature is deprecated
		# If the string begins with any other value, the radix is 10 (decimal)
	*/
	var tempH1 = parseInt(h1.value,10);
	if(tempH1 < 12 && t1.value == 'PM') {
		tempH1 = tempH1 + 12;
	}
	if(tempH1 == 12 && t1.value == 'AM') {
		tempH1 = 0;
	}
	var tempH2 = parseInt(h2.value,10);
	if(tempH2 < 12 && t2.value == 'PM') {
		tempH2 = tempH2 + 12;
	}
	if(tempH2 == 12 && t2.value == 'AM') {
		tempH2 = 0;
	}
	
	// set the times on the dates objects
	time1.setHours(tempH1,parseInt(m1.value));
	time2.setHours(tempH2,parseInt(m2.value));
	
	// calculate time difference in milliseconds
	var timeDiff = time2.getTime() - time1.getTime();
	timeDiff = timeDiff / 1000 / 60; // returns total minutes
	
	var timeDiffH = Math.floor(timeDiff / 60);	// return hours
	var timeDiffM = timeDiff - timeDiffH * 60;	// returns minutes
	
	if(d) {
		d.innerHTML 
			= 'Duration: ' 
				+ String(timeDiffH) + 'h ' 
				+ String(timeDiffM) + 'm';
	}
}

/* COOKIE HANDLING */
function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		//while (c.charAt(0)==' ') c = c.substring(1,c.length);
		c = c.replace(/\s*/,'');
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		//if (c.indexOf(nameEQ) >= 0) return c
	}
	return null;
}
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
	setCookie(name,"",-1);
}

// appHome = dynamic variable defined from script
try {
YAHOO.example.onMenuBarReady = function() {
	
	// "beforerender" event handler for the menu bar

	// Instantiate and render the menu bar
	var oMenuBar = new YAHOO.widget.MenuBar("menu", { autosubmenudisplay:true, showdelay:0, hidedelay:750, lazyload:true });

	// Render the menu bar
	oMenuBar.render();
	
}
} catch (e) {}

function refreshContent() {
	var lnk = location.href;
	if(location.href.indexOf('?') < 0) {
		lnk += '?';
	}
	if(location.href.indexOf('cachetime') < 0) {
		lnk += '&cachetime=0';
	}
	location.href = lnk;
}

function sendPwd() {
	var e = ge('email');
	if(e.value == '') {
		setBackGround(e,REQUIRED_COLOR);
		alert('Please provide an email address.');
	} else {
		if(e.value.indexOf('.') < 0 
			|| e.value.indexOf('@') < 0) {
			//alert('ok');	
			setBackGround(e,INVALID_COLOR);
			alert('A valid email is required.');
		} else {
			location.href = appHome + 'index.cfm?fuseaction=pwd.send&email=' + e.value;
		}
	}
}

function testURL() {
	var strURL = ge('URL').value;
	if(strURL != '') {
		window.open(strURL,'_blank','');
	}
}

function dispTestURLlink() {
	var u = ge('testURLlink');
	if(ge('URL').value != '') {
		u.style.display = 'inline';
	} else {
		u.style.display = 'none';
	}
}

function togWorship(aLink,j) {
	//toggleLayer(ge('worship_1'));
	//toggleLayer(ge('worship_2'));
	ge('worship_1').style.display = 'none';
	ge('worship_2').style.display = 'none';
	var myA = ge('wLinks').getElementsByTagName('a');
	for(var i=0;i<myA.length;i++) {
		myA[i].className = '';
		myA[i].blur();
		ge('worship_' + j).style.display = '';
	}
	aLink.className = 'selected';
}	

// revised 10/9/2006 -jp -for faster performance with longer lists
// revised 5/3/2007 -jp - looking for a 3rd argument in the value to make the selection (for sublists)
function checkAll(objCB,arrFlds) {
	// locate all checkboxes except for the indicator
	// example: <input type="checkbox" id="selectAll_1" checked onclick="checkAll(this,this.form.contact);" />
	// the inputs should all have the same name i.e. "contact" in this example	
	var chk = objCB.checked;
	var fld = 0;
	// 10/17/2006 - jp - bug found when only one checkbox is in the array
	if (arrFlds.type == 'checkbox') {
		arrFlds.checked = chk;
		return true;
	}
	// if multiple are found, check them all
	if(arrFlds.length) {
		fld = arrFlds.length;
		for(var j=0;j<fld;j++) {
			if(!arrFlds[j].disabled) {
				if(arguments[2]) {	// if there is a third value, check for the value in the cb
					if(arrFlds[j].id.indexOf(arguments[2]) >= 0) {
						arrFlds[j].checked = chk;
					}
				} else {
					arrFlds[j].checked = chk;
				}
				checkThisBox(arrFlds[j]);
			}
		}
		return true;
	} 
}

var allowedKeys = new Array();
allowedKeys = [8,9,16,17,18,19,27,33,34,35,36,37,38,39,40,44,45,46,91,116,144,145];
/*
	Allowed IE/Firefox keycodes
	8	BACKSPACE
	9	TAB
	16	SHIFT
	17	CTRL
	18	ALT
	19	BREAK
	27	ESC
	
	33	PAGE UP
	34	PAGE DOWN
	35	END
	36	HOME
	37	ARROW LEFT
	38	ARROW UP
	39	ARROW RIGHT
	40	ARROW DOWN
	44	PRINT SCREEN
	45	INSERT
	46	DELETE
	
	91	WINDOWS
	116	F5
	144	NUM LOCK
	145	SCROLL LOCK
	
*/

/*
	Usage:
	<textarea name="comment_tx" id="comment_tx" cols="50" rows="5" maxlength="2000"
		onkeypress="return isMaxLength(this,event);"
		onkeyup="return isMaxLength(this,event);"
		style="overflow:visible;height:100px;"></textarea>
*/
function isMaxLength(obj,e) {
	var mlength = obj.getAttribute ? parseInt(obj.getAttribute('maxlength')) : '';
	
	var msgID = obj.id + '_msg';
	var msg = ge(msgID);
	// check for message text
	if (!msg) {
		msg = document.createElement('div');
		msg.id = msgID;
		msg.className = 'small';
		obj.parentNode.appendChild(msg);
	}
	msg.innerHTML = obj.value.length + ' of ' + mlength + ' characters used';
	
	var isAllowedKey = false;
	//alert(e.keyCode);
	for (i=0;i<allowedKeys.length;i++) {
		if(parseInt(e.keyCode) == parseInt(allowedKeys[i])) {
			//alert(e.keyCode);
			isAllowedKey = true;
			break;
		}
	}
	if(isAllowedKey) {
		return true;
	}
	//alert('continuing');
	
	if (obj.getAttribute && obj.value.length==mlength) {
		return false;
	}
	if (obj.getAttribute && obj.value.length>mlength) {
		obj.value=obj.value.substring(0,mlength);
		return false;
	}
	return true;
}

var allCaps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numChars = '0123456789';
var realNumChars = numChars + '-.';
var phoneChars = numChars + '-';
var dateChars = numChars + '/';

// USAGE: <input type="text" onKeyPress="return allowChar(this,phoneChars,event);">
function allowChar(obj,allowedChars,e) {
	var key = '';
	var KEY_SPECIAL = '';
	var isAllowedKey = false;

	for (i=0;i<allowedKeys.length;i++) {
		if(parseInt(e.keyCode) == parseInt(allowedKeys[i])) {
			//alert(e.keyCode);
			isAllowedKey = true;
			break;
		}
	}
	// increment/decrement dates
	changeDate(obj,e);
	
	if(isAllowedKey) {
		return true;
	}

	if(document.all) {
		key = String.fromCharCode(e.keyCode).toLowerCase();		// IE
		if (allowedChars.indexOf(key)<0) {
			return false;
		}
	} else {
		key = String.fromCharCode(e.which).toLowerCase();		// Firefox/Netscape
		if (allowedChars.indexOf(key)<0) {
			return false;
		}
	}
}

function changeDate(obj,e) {
	var myDate = new Date();
	var month, day, year;
	var arrDt = new Array(1);
	
	if(isDate(obj.value)) {
		myDate = new Date(obj.value);
	} else {
		return;
	}
	
	obj.setAttribute('autocomplete','off');
	
	if(e.keyCode == 38) {
		// pressed up arrow in FF
		myDate.setDate(parseInt(myDate.getDate(),10)+1);
		obj.value = formatDate(myDate,'MM/dd/yyyy');	// from CalendarPopup.js
	}
	if(e.keyCode == 40) {
		// pressed down arrow in FF
		myDate.setDate(parseInt(myDate.getDate(),10)-1);
		obj.value = formatDate(myDate,'MM/dd/yyyy');	// from CalendarPopup.js
	}
}

/*
reformats dates entered as m/d/yyyy to mm/dd/yyyy
*/
function reformatDate(inp) {
	var d = inp.value;
	if(d.length==0) {
		return;
	}
	d = d.replace(/\/\//gi,'/');	// replace double slashes
	var parsedDate = new Date(d);
	var month = (parsedDate.getMonth() + 1).toString();
	var date = parsedDate.getDate().toString(); //date is the day of the month
	var year = parsedDate.getFullYear().toString();
	if(month.length == 1)
		month = '0' + month;
	if(date.length == 1)
		date = '0' + date.toString();
	parsedDate = month + '/' + date + '/' + year;
	inp.value = parsedDate;
}


function jump(thisNum,e,max,action) {
    if (document.layers) {
        if (e.target.value.length >= max)
            eval(action);
    }
    else if (document.all){
        if (thisNum.value.length > (max-1))
            eval(action);
    }
}
function insertDash() { 
	var TaxIDLength;
  	TaxIDLength = document.forms[0].TaxID.value.length;
  	if (TaxIDLength==2){
  		document.forms[0].TaxID.value += "-";
  	}
  	var SSNLength;
  	SSNLength = document.forms[0].SSN.value.length;
  	if (SSNLength==3 || SSNLength==6){
  		document.forms[0].SSN.value += "-";
  	}
}
	
function loadAndStripe() {	
	// automatically stripe the table, if any are found
	var docTable = document.getElementsByTagName('table');
	for(var i=0;i<docTable.length;i++) {
		if(docTable[i].className.indexOf('report') >= 0) {
			stripeTable(docTable[i]);
			//docTable[i].style.border = '1px solid red';
		}
	}
	//stripeTable(ge('summaryTable'));
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function checkShape(s) {
	if(s=='Other') ge('specify').style.display = ''
	else ge('specify').style.display = 'none'
}

function confirmDelete() {
	return confirm("Please confirm you would like to remove this item.\n[ WARNING: This action is irreversible. ]");
}

// automatically sets focus to the first non-empty field
function setFocus() {
	if(location.href.indexOf('#') > 0) {
		return;	
	}
	for(z=0;z<document.forms.length;z++) {
		for (i=0;i<document.forms[z].elements.length;i++) {
			if(document.forms[z].elements[i].value == '' 
				&& document.forms[z].elements[i].getAttribute("type") != 'hidden') {
				try {
					document.forms[z].elements[i].focus();
				} catch(e) {
					window.status = document.forms[z].elements[i].name + ' couldn\'t accept focus';
					var timer = window.setTimeout("window.status = 'Done.'",3*1000);
				} 
				break;
			}
		}
	}
}

function toggleLayer(o) {
	if(o.style.display == 'none') o.style.display = ''
	else o.style.display = 'none'
}

// form formatting functions
	// http://www.novell.com/documentation/extendas35/docs/help/books/TechFormValidation.html
	// USAGE:  <input name="phone" type="text" onBlur="formatPhone(this);">
	function formatPhone(obj) {
		obj.className = '';
		if (obj.value != '') {
			var bool = formatString(obj.value,/\d{3}-\d{3}-\d{4}/);
			if (!bool) {	// error found
				obj.className = 'required';	
				alert('Expecting phone format 000-000-0000');
				
				obj.focus();
			}
			return bool;
		}
	}
	
	// USAGE:  <input name="DSN" type="text" onBlur="formatDSN(this);">
	function formatDSN(obj) {
		obj.className = '';
		if (obj.value != '') {
			var bool = formatString(obj.value,/\d{3}-\d{4}/);
			if (!bool) {	// error found
				obj.className = 'required';	
				alert('Expecting DSN format 000-0000');
				obj.focus();
			}
			return bool;
		}
	}
	
	// USAGE:  <input name="dateInput" type="text" onBlur="formatDate(this);">
	function formatDate(obj) {	// assuming mm/dd/yyyy
		obj.className = '';
		if (obj.value != '') {
			var bool = formatString(obj.value,/\d{2}\/\d{2}\/\d{4}/);
			if (!bool) {	// error found
				obj.className = 'required';	
				alert('Expecting date format mm/dd/yyyy');
				obj.focus();
			}
			return bool;
		}
	}
	
	function formatString(str,pattern) {
		// format a string based on what is passed in 
		// 999-999-9999
		var retVal = true;
		//pattern = /\d{3}-\d{3}-\d{4}/;
		if (!pattern.test(str)) {
			//document.forms[0].elements[2].focus();
			retVal = false;
		}
		return retVal;
	}
	

function clearSearch(obj,def) {
	if(obj.value == def) {
		obj.value = '';
		return;
	}
	if(obj.value == '') {
		obj.value = def;
		return;
	}
}

function doFCK(objTxtBx) {
	//FCKeditor( instanceName, width, height, toolbarSet, value )
	if(objTxtBx.className.indexOf('basic')>=0) {
		var oFCKeditor = new FCKeditor( objTxtBx.name, '100%', '250px' ) ;		//, 'Basic'
		oFCKeditor.ToolbarSet = 'Basic';	// 'Full';
		} else {
		var oFCKeditor = new FCKeditor( objTxtBx.name, '100%', '400px' ) ;		//, 'Basic'
	}
	oFCKeditor.BasePath = appHome + 'fckeditor/';	// apphome defined dynamically in header
	//oFCKeditor.Value = '' ;
	//oFCKeditor.Create() ;
	oFCKeditor.ReplaceTextarea() ;
}

function initFCK() {
	var arrTA = document.getElementsByTagName('textarea');
	for(var j=0;j<arrTA.length;j++) {
		if(arrTA[j].className.indexOf('fck')>=0) {
			doFCK(arrTA[j]);
		}
	}
}

// quickly search through a select object for a particular string and selects it
/*
<input id="quickFindInp" onkeyup="quickFind(this.value,ge('bas_con_upc_id'));" 
	type="text" size="13" class="small" />
*/

// quickly search through a select object for a particular string and selects it
function quickFind(e) {
	e = e || event;		// if e parameter isn't defined, use IE's 'event' var
	var obj = ge((e.srcElement || e.target).id);
	if(!obj) return;
	
	var str = obj.value;
	var selObj = ge(obj.getAttribute('target'));
	
	// make sure the target object is a select field
	if(selObj.type.indexOf('select') < 0) return;
	
	if(str.length==0)
		return;
	
	// start w/ first option
	selObj.options[0].selected = true;
	// loop through each option's text
	for(var i=0;i<selObj.length;i++) {
		selObj.options[i].selected = false;		// default for multi-select 
		// if the str is found, then select the option and exit
		if(selObj.options[i].text.toUpperCase().indexOf(str.toUpperCase()) >= 0
			|| selObj.options[i].value.toUpperCase().indexOf(str.toUpperCase()) >= 0) {
			selObj.options[i].selected = true;	// select the option
			selObj.options[i].setAttribute('selected',true);	// IE6
			break;
		}
	}
}

// adds quickFind function to the select box
function doQuickFind(e) {
	e = e || event;		// if e parameter isn't defined, use IE's 'event' var
	var obj = ge((e.srcElement || e.target).id);
	if(!obj) return;
	var myId = 'quick_'+obj.id;
	var myQf = ge(myId);
	
	// hide any current targets
	if (targetObj) {
		targetObj.style.display = 'none';
	}
	
	if(myQf == null) {
		// create if not exists
		var myDiv = document.createElement('div');
		myDiv.style.position = 'absolute';
		myDiv.style.padding = '0px';
		myDiv.style.width = '130px';
		myDiv.id = myId;
		
		var myIfrm = document.createElement('iframe');
		myIfrm.style.position = 'absolute';
		myIfrm.style.width = '125px';
		myIfrm.style.height = '23px';
		myIfrm.style.opacity = '0.00';
		myIfrm.style.filter = 'alpha(opacity=0)';
		myIfrm.style.zIndex = 0;
		//myIfrm.src = 'about:blank';
		myDiv.appendChild(myIfrm);		// attach iframe to div
		
		var myLbl = document.createElement('label');
		myLbl.className = 'quick';
		myLbl.setAttribute('for',myId + '_inp');
		myLbl.innerHTML = 'Find:'
		myLbl.title = 'Type here to quickly find an option...';
		myDiv.appendChild(myLbl);		// attach label to div
		
		var myInp = document.createElement('input');
		myInp.id = myId + '_inp';
		myInp.typeOf = 'text';
		myInp.setAttribute('target',obj.id);
		// attach event to search when typing in the input
		addEvent(myInp,'keyup',quickFind);	// IE6
		myLbl.appendChild(myInp);	// attach input to label
		myInp.style.zIndex = 10;
		
		//<img alt="close" src="/media/close.gif"/>
		var myClose = document.createElement('img');
		//myClose.className='close';
		myClose.title='close';
		myClose.setAttribute('alt','close');
		myClose.setAttribute('src','../../Image/Check_x.gif');
		myClose.style.marginLeft='2px';
		myClose.style.marginBottom='9px';
		myClose.style.cursor='pointer';
		addEvent(myClose,'click',function anonymous(){targetObj.style.display='none'});
		myLbl.appendChild(myClose);	// attach closer to label
		
		var myBr = document.createElement('br');
		myBr.setAttribute('clear','left');
		
		obj.parentNode.insertBefore(myBr,obj.nextSibling);	// attach break
		obj.parentNode.insertBefore(myDiv,myBr.nextSibling);	// attach quick finder label/input
		
		targetObj = myDiv;
	}
	if(myQf) {
		targetObj = myQf;	// sets the click object to hide when blurred
		myQf.style.display = 'block';
	}
	return;
}

// loop through all the select fields and determine if they need a helper quickfind
function applyQuickFind() {	
	var docSelect = document.getElementsByTagName('select');
	for(var i=0;i<docSelect.length;i++) {
		if(docSelect[i].length >= 20) {
			addEvent(docSelect[i],'mouseover',doQuickFind);
		}
	}
}

function isChild(s, d) {
	while (s) {
		if (s == d) {
			return true;
		}
		s = s.parentNode;
	}
	return false;
}
// hides an object
function checkClick(e) {
	e ? evt = e : evt = event;
	CSE = evt.target ? evt.target : evt.srcElement;
	if (targetObj) {
		if (!isChild(CSE, targetObj)) {
			targetObj.style.display = "none";
		}
	}
}
document.all ? document.attachEvent("onclick", checkClick) : document.addEventListener("click", checkClick, false);

function Left(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	} else {
		if (obj.x) {
			curleft += obj.x;
		}
	}
	return curleft;
}
function Top(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else {
		if (obj.y) {
			curtop += obj.y;
		}
	}
	return curtop;
}

function alignTo(objParent,objChild) {
	objChild.style.left = Left(objParent) + "px";
	var offSet = 0;
	if(this.offsetHeight != undefined) {
		offSet = this.offsetHeight;
	}
	objChild.style.top = Top(objParent) + offSet + "px";
	if(arguments[2] != undefined) {
		objChild.style.width = arguments[2] + "px";
	}
	objChild.style.display='';
}

var inited = false;

// iniitial functions to run onload (called from slideshow.js)
function init() {
	if(!inited) {
		try {
			initFCK();
		} catch(e) {}
		inited = true;
	}
	try {
		setFocus();
	} catch(e) {}
	try {
		loadAndStripe();
	} catch(e) {}
	try {
		applyQuickFind();
	} catch(e) {}
}

window.onload = init;	