//-----------------------------
function stopEnterKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}
document.onkeypress = stopEnterKey;
//-----------------------------
function rnd(){
	return String((new Date()).getTime()).replace(/\D/gi,'')
}
//-----------------------------
function showDiv(boxid){
	if(!document.getElementById(boxid)) return;
	document.getElementById(boxid).style.visibility="visible";
	document.getElementById(boxid).style.display="block";
}
//-----------------------------
function hideDiv(boxid){
	if(!document.getElementById(boxid)) return;
	document.getElementById(boxid).style.visibility="hidden";
	document.getElementById(boxid).style.display="none";
}
//-----------------------------
function toggleHideDiv(boxid){
	// if clicked, show if hidden, hide if visible
	if(!document.getElementById(boxid)) return;
	var boxStyle = document.getElementById(boxid).style; 
	if(boxStyle.visibility == "hidden" || boxStyle.display == "none"){
		boxStyle.visibility ="visible";
		boxStyle.display = "block";
	}
	else{
		boxStyle.visibility ="hidden";
		boxStyle.display = "none";
	}
}
//-----------------------------
function removeElement(divNum,toThisParent) {
	if(toThisParent == null){
		toThisParent = 'blankDivParent';
	}
	var parentObject = document.getElementById(toThisParent);
	var oldDiv = document.getElementById(divNum);
	parentObject.removeChild(oldDiv);
}
//-----------------------------
function addSequentialElement(toThisParent) {
	if(toThisParent == null){
		toThisParent = 'blankDivParent';
	}
	var ni = document.getElementById(toThisParent);
	var numi = document.getElementById('blankDivIdValue');
	var num = (document.getElementById('blankDivIdValue').value -1)+ 2;
	numi.value = num;
	var newdiv = document.createElement('div');
	var divIdName = 'new'+num+'Div';
	newdiv.setAttribute('id',divIdName);
	ni.appendChild(newdiv);
	return (divIdName);
}
//-----------------------------
function checkDropDown(selectBoxToWorkWith){
	thisDropDown = document.getElementById(selectBoxToWorkWith);
	selectedValue = thisDropDown.value;
	if(selectedValue == -1){
		// "add new item" was chosen
		changeSelectToInput(selectBoxToWorkWith);
	}
	selectBoxToWorkWithNoNumbers = selectBoxToWorkWith.replace(/[^\d]/g, "");
	if(selectBoxToWorkWith.indexOf('elementTypes')>-1){
		if(selectedValue == 2 || selectedValue == 29){
			// 2 is Hymn chosen, 29 is Chorus chosen, show right list:
			status("Getting songs: " + selectBoxToWorkWith);
			getResponse("application.php?doAction=showElements&elementType=" + selectedValue + "&sequentialJavascriptId=" + selectBoxToWorkWithNoNumbers,"newElement"+selectBoxToWorkWithNoNumbers);
		}
	}
	else if(selectBoxToWorkWith.indexOf('role')>-1){
		// Role drop down selected, change the person drop down to only those in this role
		if(thisDropDown.value > 0){
			// Sometimes this gives a javascript error, I think because it cannot find the div to insert the response into. 
			// I know this happens on the Schedule page. It might happen elsewhere.
			getResponse("application.php?doAction=showRolesPeople&roleType=" + thisDropDown.value + "&sequentialJavascriptId=" + selectBoxToWorkWithNoNumbers,"newElement"+selectBoxToWorkWithNoNumbers);
		}
	}
}
//-----------------------------
function changeSpanToInput(spanToChange){
	spanObject = document.getElementById(spanToChange);
	newInputBox = document.createElement('input');
	newInputBox.setAttribute('name',spanToChange);
	newInputBox.setAttribute('id',spanToChange + 'Input');
	var inputValue = spanObject.innerHTML.replace('&nbsp;','');
	newInputBox.setAttribute('value',inputValue);
	newInputBox.setAttribute('onblur',"submitQueryToServer('" + spanToChange + "Form','application.php?doAction=updateMiscField&field=" + spanToChange + "', '" + spanToChange + "');document.getElementById('" + spanToChange + "').style.display='inline';document.getElementById('" + spanToChange + "' + 'Input').parentNode.removeChild(document.getElementById('" + spanToChange + "' + 'Input'));");
	spanObject.parentNode.insertBefore(newInputBox,spanObject);
	spanObject.style.display = "none";
	newInputBox.focus();
}
//-----------------------------
function changeSelectToInput(selectToChange){
	selectObject = document.getElementById(selectToChange);
	newInput=document.createElement('input');
	newInput.type='text';
	newInput.setAttribute('name',selectObject.name);
	newInput.setAttribute('id',selectObject.id);
	newInput.setAttribute('onblur','addItemToDropDown(\''+ selectToChange + '\')');
	selectObject.parentNode.insertBefore(newInput,selectObject);
	selectObject.parentNode.removeChild(selectObject);
	newInput.focus();
}
//-----------------------------
function addItemToDropDown(fieldName){
	var tableToSave = fieldName.replace(/[\d]+/,"");
	var fieldNum = fieldName.replace(/[a-z]+/i,"");
	var newValue = document.getElementById(fieldName).value;
	getResponse("application.php?doAction=addToDropdown&table="+tableToSave+"&value="+newValue+"&sequentialJavascriptId=" + fieldNum,fieldName+'Wrapper');
}
//-----------------------------
function editServicesRow(serviceId,rowId){
	var rowIdNumber = rowId.replace(/[^\d]/g, "");
	var newWrapperDiv=document.createElement('div');
	var currentRow = document.getElementById(rowId);
	currentRow.parentNode.insertBefore(newWrapperDiv,currentRow);
	newWrapperDiv.setAttribute('id','parent'+rowIdNumber);
	newWrapperDiv.setAttribute('class','inlineDiv');
	newWrapperDiv.style.position='absolute';
	currentRow.style.visibility = "hidden";
	getResponse("application.php?doAction=editServiceRow&order_id="+rowIdNumber+"&service_id="+serviceId,'parent'+rowIdNumber);
}
//-----------------------------
function status(content){
	var feedBack = document.getElementById('feedBack');
	feedBack.innerHTML = content;
	showDiv('feedBack');
	setTimeout("hideDiv('feedBack')", 3000);
}
//-----------------------------
function clientSideInclude(id, url) {
	var req = false;
	if (window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		}
		catch (e) {
			req = false;
		}
	}
	else if (window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e) {
				req = false;
			}
		}
	}
	var element = document.getElementById(id);
	if (!element) {
		alert("Bad id " + id + "passed to clientSideInclude." +	"You need a div or span element " + "with this id in your page.");
		return;
	}
	if (req) {
		req.open('GET', url, false);
		req.send(null);
		element.innerHTML = req.responseText;
	}
	else {
		element.innerHTML =
			"Sorry, your browser does not support XMLHTTPRequest objects. This page requires " +
			"Internet Explorer 5 or better for Windows, or Firefox for any system, or Safari. Other " +
			"compatible browsers may also exist.";
	}
}
//-----------------------------
function zebraStripe(id) {
		var even = false; //flag
	  	// arguments can be used, otherwise defaults are:
		var evenColor = arguments[1] ? arguments[1] : "#fff";
		var oddColor = arguments[2] ? arguments[2] : "#eee";
		var table = document.getElementById(id); // reference to desired table
		if (! table) { return; } // abort?
		var tbodies = table.getElementsByTagName("tbody");
		for (var h = 0; h < tbodies.length; h++) { 	// and iterate through tbodies
			// find all the <tr> elements... 
			var trs = tbodies[h].getElementsByTagName("tr");
			for (var i = 0; i < trs.length; i++) { // iterate
				// avoid rows that have a class attribute
				// or backgroundColor style
				if (!trs[i].style.backgroundColor) {
					// get all the cells in this row...
					var tds = trs[i].getElementsByTagName("td");
					// and iterate through them...
					for (var j = 0; j < tds.length; j++) {
						var mytd = tds[j];
						// avoid cells that have a class attribute
						// or backgroundColor style
						if (!hasClass(mytd) && !mytd.style.backgroundColor) {
							mytd.style.backgroundColor = even ? evenColor : oddColor;
						}
					}
				}
				even =  ! even; // flip from odd to even, or vice-versa
			}
		}
	}
	function hasClass(obj) { // part of zebraStripe
		var result = false;
		if (obj.getAttributeNode("class") != null) {
			result = obj.getAttributeNode("class").value;
		}
	return result;
}   
//-----------------------------
function filterList(textEntryBox,tableId){
	textQuery = textEntryBox.value.toLowerCase();
	var table = document.getElementById(tableId);
	for(var countRow=0; countRow < table.rows.length; countRow++){
		var row = table.rows[countRow];
		var cell = row.cells[0];
		content = cell.innerHTML;
		content = content.replace(/<[^<>]*>/g, "");
		content = content.toLowerCase();
		if(content.indexOf(textQuery) == -1){
			row.style.display = "none";
		}
		else{
			row.style.display = "block";
		}
	}
}
//-----------------------------
function areNewElementFieldsFilledIn(){
	// check radio
	var radios = document.getElementsByTagName('input');
	var elementValue;
	for (var i = 0; i < radios.length; i++) {
		if (radios[i].type === 'radio' && radios[i].checked) {
			// get value, set checked flag or do whatever you need to
			elementValue = radios[i].value;     
		}
	}
	// check name and author
	if(document.getElementById('name').value.length < 1){
		alert('Please enter a name for this element.');
		return false;
	}
	if(document.getElementById('author').value.length < 1){
		alert('Please enter an author for this element.');
		return false;
	}
	if(!elementValue){
		alert('Please choose an element type.');
		return false;
	}
	else{
		return true;
	}
}
//-----------------------------
function toggleButtonValue(objectId,offValue,onValue){
	theButton = document.getElementById(objectId);
	if(theButton.value == offValue){
		theButton.value = onValue;
	}
	else{
		theButton.value = offValue;
	}
}
//-----------------------------
function screenResolution(){
	var width = document.documentElement.clientWidth;
	if (width < 920){
		alert('Your screen is set to ' + width + ' pixels wide. This site is best viewed with a wider screen resolution. You should try to adjust your resolution using display settings in your control panel, or if possible maximize your window.');
	}
}
//-----------------------------
var imgObj = new Array;
function splashImagesToDOM(){
	var splashID = "splash";
	// first create the images in divs, appended to existing image
	imageArray.sort( randOrd );
	var parentDiv = document.getElementById(splashID);
	if(parentDiv){
		for(var i=0; i<imageArray.length; i++) { 
			var newDiv = document.createElement("DIV");
			parentDiv.appendChild(newDiv);
			newDiv.setAttribute('id',splashID + i);
			newDiv.style.width = "100%";
			newDiv.style.height = "100%";
			newDiv.style.position = "absolute";
			newDiv.style.top = "0";
			newDiv.style.left = "0";
			newDiv.style.background = "url(" + imageArray[i] + ")";
			newDiv.style.backgroundRepeat = "no-repeat";
			newDiv.style.backgroundPosition = "0px 0px";			
			newDiv.style.overflow = "hidden";
			newDiv.style.display = "none";
			newDiv.style.zIndex = "auto";
			imgObj.push(document.getElementById(splashID + i));
			imgObj[i].xOpacity = 0;
		}
		// now begin crossfading the images:
		imgObj[0].xOpacity = .99;
		crossFadeSplashImages(0);
	}
}
function randOrd(){
	return (Math.round(Math.random())-0.5); 
}

//-----------------------------
var current=0;
function crossFadeSplashImages(){
	var currentOpacity = imgObj[current].xOpacity;
	var nextIndex = imgObj[current+1]?current+1:0;
	var nextOpacity = imgObj[nextIndex].xOpacity;
	currentOpacity-=.05; 
	nextOpacity+=.05;
	imgObj[nextIndex].style.display = "block";
	imgObj[current].xOpacity = currentOpacity;
	imgObj[nextIndex].xOpacity = nextOpacity;

	setOpacity(imgObj[current]); 
	setOpacity(imgObj[nextIndex]);

	if(currentOpacity<=0) {
		imgObj[current].style.display = "none";
		current = nextIndex;
		setTimeout(crossFadeSplashImages,4000);
	} else {
		setTimeout(crossFadeSplashImages,40);
	}
	function setOpacity(obj) {
		if(obj.xOpacity>.99) {
			obj.xOpacity = .99;
			return;
		}
		obj.style.opacity = obj.xOpacity;
		obj.style.MozOpacity = obj.xOpacity;
		obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
	}
}
//-----------------------------
var timeoutHolder = null;
function doSplashCollapse() {
	if (parseInt(splashDiv.style.height) > 0){
		splashDiv.style.height 	= parseInt(splashDiv.style.height)	-10 + 'px';
		overlayDiv.style.height = parseInt(overlayDiv.style.height)	-10 + 'px';
		timeoutHolder = setTimeout(doSplashCollapse,30);
	}
	else{
		clearTimeout(timeoutHolder);
	}
}
function doSplashExpand(){
	if (parseInt(splashDiv.style.height) < 420){
		splashDiv.style.height	= parseInt(splashDiv.style.height) 	+10 + 'px';
		overlayDiv.style.height	= parseInt(overlayDiv.style.height) +10 + 'px';
		timeoutHolder = setTimeout(doSplashExpand,30);
	}
	else{
		clearTimeout(timeoutHolder);
	}
}
function collapseSplash() {
	splashDiv = document.getElementById('splash'); 
	overlayDiv = document.getElementById('splashOverlay');
	if(parseInt(splashDiv.style.height) >  10 || isNaN(parseInt(splashDiv.style.height))){
		splashDiv.style.height = '444px';
		overlayDiv.style.height = '444px';
		doSplashCollapse();
	}
	setCookie('splashExpanded', 0);
}
function expandSplash() {
	clearTimeout(timeoutHolder);
	splashDiv = document.getElementById('splash'); 
	overlayDiv = document.getElementById('splashOverlay');
	if(parseInt(splashDiv.style.height) <  10 || isNaN(parseInt(splashDiv.style.height))){
		splashDiv.style.height = '0px';
		overlayDiv.style.height = '0px';
		doSplashExpand();
	}
	setCookie('splashExpanded', 1);
}
//-----------------------------
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 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);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
//-----------------------------
function eraseCookie(name) {
	createCookie(name,"",-1);
}
//-----------------------------
function zoomImage(image){
	// make div with a gray transparent background
	var newDivWrapper = document.createElement("div");
	newDivWrapper.setAttribute('id',"zoomImageWrapper");
	//newDivWrapper.setAttribute('onclick', "document.body.removeChild(document.getElementById('zoomImageWrapper'));"); 
	newDivWrapper.style.width = "100%"; 
	newDivWrapper.style.height = "100%";
	newDivWrapper.style.position = "fixed";
	newDivWrapper.style.top = 0;
	newDivWrapper.style.left = 0;
	newDivWrapper.style.zIndex = "1999";
	newDivWrapper.style.backgroundImage = "url('/images/gray-transparency.png')";
	document.body.appendChild(newDivWrapper);
	// make div child, which has background of image we are 'zooming'
	var newDiv = document.createElement("div");
	newDiv.setAttribute('id', "zoomImage"); 
	newDiv.setAttribute('onclick', "nextImage('" + image + "');"); 
	newDiv.style.width = "100%"; 
	newDiv.style.height = "100%";
	newDiv.style.position = "fixed";
	newDiv.style.top = 0;
	newDiv.style.left = 0;
	newDiv.style.zIndex = "2000";
	newDiv.style.cursor = "pointer";
	//newDiv.style.backgroundColor = "#efefef";
	newDiv.style.backgroundImage = "url(" + image + ")"; 
	newDiv.style.backgroundRepeat = "no-repeat";
	newDiv.style.backgroundPosition = "center center";
	document.getElementById('zoomImageWrapper').appendChild(newDiv);
}
function nextImage(image){
	image = image.replace("http://" + location.hostname,'');
	// get all images
	var allImages = document.getElementById('content').getElementsByTagName("img");
	for (var i = 0; i < allImages.length; i++) {
		//var filename = allImages[i].src.replace(/^.*[\\\/]/, '')
		var filename = allImages[i].src.replace(/thumb-/,'');
		filename = filename.replace("http://" + location.hostname,'');
		if(filename == image){
			// we wamt next image, or if last, quit;
			i++;
			if(i < allImages.length){
				filename = allImages[i].src.replace(/thumb-/,'');
				document.body.removeChild(document.getElementById('zoomImageWrapper'));
				zoomImage(filename);
				break;
			}
			else{
			//alert(i);
				document.body.removeChild(document.getElementById('zoomImageWrapper'));
			}
		}
	}
	//document.body.removeChild(document.getElementById('zoomImageWrapper'));
}

