
/////////////////////////////////
// NOW PLAYING       ////////////
/////////////////////////////////
function initNowPlaying() {
	
	function nowPlay() {
		var req2 = new Request.HTML({ url:"/includes/nowplaying.php", method:'get', urlEncoded:true, evalScripts:true, evalResponse:true, 
			onSuccess: function(html) {
				$('nowPlayingText').innerHTML = "";
				$('nowPlayingText').adopt(html);
			}
		}).send();
	};

	var req1 = new Request.HTML({ url:"/includes/nowplaying.php", method:'get', urlEncoded:true, evalScripts:true, evalResponse:true, 
		onSuccess: function(html) {
			$('nowPlayingText').innerHTML = "";
			$('nowPlayingText').adopt(html);
			nowPlay.periodical(240000);
		}
	}).send();
}


function popUpPlayer() {
	window.open("http://www.streamaudio.com/player/player.aspx?optin=no&station=KSGN_FM", "popUpPlayer", "location=0,status=0,scrollbars=0,width=520,height=260");
}


/////////////////////////////////
// TOP NAVIGATION    ////////////
/////////////////////////////////
var theLinks = $$("#nav a");
var dropOver = false;

function initNav() {
	var theLinks = $$("#nav a");
	theLinks.each(function(theLink) {
		var dropBox = (theLink.getProperty('rel')) ? $(theLink.getProperty('rel')): null;
		theLink.addEvent('mouseover', function() { 
			if(dropBox != null) toggleDrop(theLink,dropBox,'over');
			toggleNavLink(theLink,'over');
		});
		theLink.addEvent('mouseout', function() { 
			if(dropBox != null && dropOver == false) toggleDrop(theLink,dropBox,'out');
			toggleNavLink(theLink,'out');
		});
		if(dropBox != null) {
			dropBox.addEvent('mouseover', function() { 
				dropOver = true;
				toggleDrop(theLink,dropBox,'over');
			});
			dropBox.addEvent('mouseout', function() { 
				dropOver = false;
				toggleDrop(theLink,dropBox,'out');	
			});
		}
	});
}
function toggleNavLink(link,state) {
	(state == "over") ? link.addClass('selected'): link.removeClass('selected');
}
function toggleDrop(link,dropBox,state) {
	var dropLeft = (Browser.Engine.gecko) ? link.getLeft()-3: link.getLeft()-4;
	//var blackOut = new Fx.Morph(dropBox, {duration:0, transition: Fx.Transitions.Cubic.easeOut, wait:false});
	(state == "over") ? link.addClass('selected'): link.removeClass('selected');
	(state == "over") ? dropBox.setStyles({'opacity':1,'display':'block','top':'124px','left':dropLeft,'z-index':'10000'}): dropBox.setStyles({'opacity':0,'display':'none'});
	//if(state == "over") blackOut.start({opacity: 1});
}


/////////////////////////////////
// ENCOURAGING THOUGHT  /////////
/////////////////////////////////
var thoughtItems;
var currentThought = 0;
var prevThought = 0;
var rotatorThought;

function initThoughtRotator() {
	if($('thoughtBox')) {
		thoughtItems = $$('#thoughtBox p');
		thoughtItems.each(function(theItem) { theItem.setStyles({'display':'none','opacity':'0'}); });
		thoughtItems[0].setStyles({'display':'inline','opacity':'1'});
		nextThoughtItem();
	}
}
function nextThoughtItem() {
	switchThought(currentThought);
	prevThought = currentThought;
	currentThought = (currentThought+1 > thoughtItems.length-1) ? 0: currentThought+1;
}
function switchThought(num) {
	
	//CLEAR OLD STUFF
	clearInterval(rotatorThought);
	thoughtItems.each(function(theItem) { theItem.setStyles({'display':'none','opacity':'0'}); });
	
	//START NEW STUFF
	var thisThought = thoughtItems[num];
	thisThought.setStyles({'display':'block'});
	var thoughtShow = new Fx.Morph(thisThought, {duration:1200, transition:Fx.Transitions.Cubic.easeOut, wait:false}).start({opacity:1});
	rotatorThought = setInterval("nextThoughtItem()", 8000);
}



/////////////////////////////////
// FEEL STUFF           /////////
/////////////////////////////////
var feelItems;
var currentFeeling = 0;
var prevFeeling = 0;
var rotatorFeeling;

function initFeelingRotator() {
	if($('feelBox')) {
		feelItems = $$('#feelBox p');
		feelItems.each(function(theItem) { theItem.setStyles({'display':'none','opacity':'0'}); });
		feelItems[0].setStyles({'display':'inline','opacity':'1'});
		nextFeelItem();
	}
}
function nextFeelItem() {
	switchFeeling(currentFeeling);
	prevFeeling = currentFeeling;
	currentFeeling = (currentFeeling+1 > feelItems.length-1) ? 0: currentFeeling+1;
}
function switchFeeling(num) {
	
	//CLEAR OLD STUFF
	clearInterval(rotatorFeeling);
	feelItems.each(function(theItem) { theItem.setStyles({'display':'none','opacity':'0'}); });
	
	//START NEW STUFF
	var thisFeeling = feelItems[num];
	thisFeeling.setStyles({'display':'block'});
	var feelShow = new Fx.Morph(thisFeeling, {duration:1200, transition:Fx.Transitions.Cubic.easeOut, wait:false}).start({opacity:1});
	rotatorFeeling = setInterval("nextFeelItem()", 5000);
}





function openPlayer(URL) {
	//IE and NS Windows
	if(navigator.platform.indexOf("Win") > -1) {
		var opt1 = 'width=472,height=257,top=420,left=520,screenY=420,screenX=520';
		var opt2 = 'width=472,height=257,top=250,left=300,screenY=250,screenX=300';
	} 
	else if(navigator.platform.indexOf("Mac") > -1) {
		//IE and NS Mac
		if(navigator.appName.indexOf("Microsoft") > -1) {
			var opt1 = 'width=455,height=240,top=420,left=520,screenY=420,screenX=520';
			var opt2 = 'width=455,height=240,top=250,left=300,screenY=250,screenX=300';
		} 
		else if(navigator.appName.indexOf("Netscape") > -1) {
			var opt1 = 'width=472,height=257,top=420,left=520,screenY=420,screenX=520';
			var opt2 = 'width=472,height=257,top=250,left=300,screenY=250,screenX=300';
		}
	}
	if(screen.width >= 1000) window.open(URL,'Streamaudio_Player',opt1);
	if(screen.width <= 800) window.open(URL,'Streamaudio_Player',opt2);
}






//EVENT CALENDAR DROP MENU
function initCalCatNav() {
	if($('calCatName')) {
		$('calCatName').addEvent('mouseover', function() { 
			toggleCalCatDrop('over');
		});
		$('calCatName').addEvent('mouseout', function() { 
			toggleCalCatDrop('out');
		});
		$$('#calCatDrop a').each(function(theA) {
			theA.addEvent('mouseover', function() { 
				toggleCalCatDrop('over');
			});
		});
		$('calCatDrop').addEvent('mouseover', function() { 
			toggleCalCatDrop('over');
		});
	}
}
function toggleCalCatDrop(state) {
	var display = (state == 'over') ? 'block': 'none';
	$('calCatDrop').setStyles({'display':display});
}
function toggleCalendar(way) {
	var calFade = new Fx.Morph('calendarTable', {duration: 200, wait: true});
	var display = (way == "on") ? "block": "none";
	if(way == "on") {
		$('calendarTable').setStyles({opacity:0,'display':display});
		calFade.start({'opacity': 1});
	}
	else {
		calFade.start({'opacity': 0})
		.chain(function() {
			$('calendarTable').setStyles({'display':display});
		});
	}
}


/////////////////////////////////
// AD ROTATOR        ////////////
/////////////////////////////////
var rotatorItems;
var rotatorButtons;
var nextItem = 0;
var currentItem = 0;
var prevItem = 0;
var firstLoad = true;
var play = true;
var rotator;
var maxItems;

function initRotator() {
	if($('flashrotator')) {
		rotatorButtons = $$('#flashrotatornav a');
		rotatorItems = $$('#flashrotatoritems .flRotItem');
		maxItems = rotatorItems.length-1;
		rotatorItems.each(function(theLink) { theLink.setStyles({'left':735}); });
		
		//LINK STUFF
		$('flashrotlink').addEvent('mouseover', function() { $('flashrotatoritems').fade(0.3); });
		$('flashrotlink').addEvent('mouseout', function() { $('flashrotatoritems').fade(1); });
		$('flashrotlink').setStyles({'display':'none'});
	
		//TEXT DISPLAY
		$('flashrottextbox').setStyles({'opacity':0, 'display':'none', 'bottom':-50});
		
		rotatorItems[0].setStyles({'left':0});
		
		
		var runOnce = (rotatorItems.length == 1) ? true: false;
		nextRotatorItem(runOnce);
	}
}
function nextRotatorItem(runOnce) {
	prevItem = currentItem;
	currentItem = (currentItem+1 > maxItems) ? 0: currentItem+1;
	currentItem = (firstLoad == false) ? currentItem: 0;
	baitAndSwitch(currentItem,runOnce);
}
function chooseRotatorItem(num) {
	prevItem = currentItem;
	currentItem = num;
	baitAndSwitch(num);
}
function baitAndSwitch(num,runOnce) {
	
	//STOP IT!
	clearInterval(rotator);
	
	//FLIP BANNERS
	var thisItem = rotatorItems[num];
	var thatItem = rotatorItems[prevItem];
	var way = (num > prevItem || firstLoad == true) ? 'prev': 'next';
	(way == "next") ? thisItem.setStyles({'left':-735}): thisItem.setStyles({'left':735});
	
	var thatOut = (way == "next") ? 735: -735;
	
	var itemShow = new Fx.Morph(thisItem, {duration:500, transition:Fx.Transitions.Cubic.easeOut, wait:true}).start({'left':0});
	if(firstLoad == false) {
		var itemHide = new Fx.Morph(thatItem, {duration:500, transition:Fx.Transitions.Cubic.easeOut, wait:true}).start({'left':thatOut})
		.chain(function() { thatItem.setStyles({'left':735}); });
	}
	
	//CLEAR OUT OLD TEXT STUFF
	$('flashrottextbox').setStyles({'opacity':0, 'display':'none', 'bottom':-50});
	$('flashRotTitle').set('html','');
	$('flashRotDesc').set('html','');
	$('flashrotlink').setStyles({'display':'none'});
	
	//GET NEW TEXT STUFF
	if(thisItem.getElement('a').getProperty('rel')) {
		var textEls = thisItem.getElement('a').getProperty('rel').split('|');
		$('flashRotTitle').set('html',textEls[0]);
		$('flashRotDesc').set('html',textEls[1]);
		$('flashrottextbox').setStyles({opacity:1,'display':'block'});
		var textShow = new Fx.Morph($('flashrottextbox'), {duration:300, transition:Fx.Transitions.Cubic.easeOut, wait:false}).start({'bottom':0});
	}
	
	//THE LINK
	var hasLink = (thisItem.getElement('a').getProperty('href')) ? true: false;
	if(hasLink) { 
		$('flashrotlink').setStyles({'display':'block'});
		$('flashrotlink').setProperties({'href':thisItem.getElement('a').getProperty('href'), 'target':thisItem.getElement('a').getProperty('target')});
	}
	
	//NAV BUTTONS
	if(!runOnce) {
		rotatorButtons.each(function(theButton) { if(!theButton.hasClass('playPauseButton')) { theButton.removeClass('selected'); } });
		rotatorButtons[num].addClass('selected');
		rotator = (play == false) ? null: setInterval("nextRotatorItem()", 8000);
	}
	else $('flashrotatornav').setStyle('display','none');
	
	//KILL FIRSTLOAD
	firstLoad = false;
}
function playPauseRotator() {
	if(play == true) {
		clearInterval(rotator);
		play = false;
		$('flRotPlayButton').setStyle('display','block').addClass('selected');
		$('flRotPauseButton').setStyle('display','none');
	}
	else {
		rotator = setInterval("nextRotatorItem()", 100);
		play = true;
		$('flRotPlayButton').setStyle('display','none').addClass('selected');
		$('flRotPauseButton').setStyle('display','block');
	}
}








/////////////////////////////////
// AUDIO PLAYER      ////////////
/////////////////////////////////
function getFlashMovieObject(movieName) {
	if(window.document[movieName]) return window.document[movieName];
	if(navigator.appName.indexOf("Microsoft Internet") == -1) {
		if(document.embeds && document.embeds[movieName])
		return document.embeds[movieName]; 
	}
	else return document.getElementById(movieName);
}
function switchSong(player, songFile, songDesc) {
	var flashMovie = getFlashMovieObject(player);
	flashMovie.SetVariable('_root.theSong',songFile);
	flashMovie.SetVariable('_root.theSongDesc',songDesc);
	flashMovie.Play();
}
function playRelatedAudio(player,songFile,songTitle) {
	$('relAudioNowPlaying').innerHTML = "<span>NOW PLAYING <b>&raquo;</b></span> "+songTitle;
	var flashMovie = getFlashMovieObject(player);
	flashMovie.SetVariable('_root.theSong',songFile);
	flashMovie.Play();
}




///////////////////////////////////////////////////
// CALENDAR SWITCHING STUFF  //////////////////////
///////////////////////////////////////////////////
function getCalendar(m,y,cal) {
	var formFade = new Fx.Morph('calendarTableInside', {duration: 100, wait: true});
	formFade.start({'opacity': 0})
	.chain(function() {
		var req = new Request({ url:'/includes/graphicCalendar.php', method:'get', data:"month="+m+"&year="+y+"&calCat="+cal, urlEncoded:true, evalScripts:true,
			onSuccess: function(txt) {
				$('calendarTableInside').set('html',txt);
				formFade.start({'opacity': 1});
			},
			onFailure: function() {
				formFade.start({'opacity': 1});
				alert('Sorry! Server is busy. Try again later.');
			}
		}).send();
	});
}


///////////////////////////////////////////////////
// PRAYER PAGE STUFF         //////////////////////
///////////////////////////////////////////////////
function togglePrayerBox(box) {
	$$('#prayerBoxContent div').each(function(theBox) {
		if(theBox.hasClass('open')) theBox.removeClass('open');
	});
	$$('#prayerBoxTop a').each(function(theLink) {
		if(theLink.hasClass('selected')) theLink.removeClass('selected');
	});
	$('prayer'+box).addClass('open');
	$(box+'link').addClass('selected');
}

function initPrayerForms() {
	
	if($('requestForm')) {
		
		var errors = false;
		
		//PRAYER REQUEST FORM
		var prayerForm = $('requestForm');
		prayerForm.addEvent('submit', function(e) {
			e.stop();
			errors = false;
			if(prayerForm.title.value == "" || prayerForm.content.value == "" || prayerForm.name.value == "" || prayerForm.email.value == "") {
				errors = true;
				alert("Please fill in all required fields.");
			}
			if(!isValidEmail(prayerForm.email.value)) {
				errors = true;
				alert("Please use a valid email address.");
			}
			if(errors == false) {
				prayerForm.setStyles({opacity:0});
				$('prayerBoxContentInside').addClass('loading');
				prayerForm.set('send', {
					onComplete: function(txt) {
						prayerForm.empty();
						prayerForm.set('html',txt);
						prayerForm.setStyles({opacity:1});
						$('prayerBoxContentInside').removeClass('loading');
					},
					onFailure: function() {
						alert('Sorry! The network was busy. Please try again later.');
						prayerForm.setStyles({opacity:1});
						$('prayerBoxContentInside').removeClass('loading');
					}
				}).send();
			}
		});
		
		//PRAYER REQUEST FORM
		var messageForm = $('messageForm');
		messageForm.addEvent('submit', function(e) {			
			e.stop();
			errors = false;
			if(messageForm.content.value == "" || messageForm.email.value == "") {
				errors = true;
				alert("Please fill in all required fields.");
			}
			if(!isValidEmail(messageForm.email.value)) {
				errors = true;
				alert("Please use a valid email address.");
			}
			if(errors == false) {
				messageForm.setStyles({opacity:0});
				$('prayerBoxContentInside').addClass('loading');
				messageForm.set('send', {
					onComplete: function(txt) { 
						messageForm.empty();
						messageForm.set('html',txt);
						messageForm.setStyles({opacity:1});
						$('prayerBoxContentInside').removeClass('loading');
					},
					onFailure: function() {
						alert('Sorry! The network was busy. Please try again later.');
						messageForm.setStyles({opacity:1});
						$('prayerBoxContentInside').removeClass('loading');
					}
				}).send();
			}
		});
		
		//SAY YOU PRAYED FORM
		var prayedForm = $('prayedForm');
		prayedForm.addEvent('submit', function(e) {
			new Event(e).stop();
			prayedForm.setStyles({opacity:0});
			$('prayerBoxContentInside').addClass('loading');
			prayedForm.set('send', {
				onComplete: function(txt) {
					prayedForm.empty();
					prayedForm.set('html',txt);
					prayedForm.setStyles({opacity:1});
					$('prayerBoxContentInside').removeClass('loading');
				},
				onFailure: function() {
					alert('Sorry! The network was busy. Please try again later.');
					prayedForm.setStyles({opacity:1});
					$('prayerBoxContentInside').removeClass('loading');
				}
			}).send();
		});
	}
}







//////////////////////////////////
// CONTACT EMAIL FORM STUFF  /////
//////////////////////////////////
function initContactEmailForm() {
	
	if($('contactEmailForm')) {
		
		var errors = false;
		
		//PRAYER REQUEST FORM
		var theForm = $('contactEmailForm');
		theForm.addEvent('submit', function(e) {
			e.stop();
			errors = false;
			if(theForm.to.options[theForm.to.selectedIndex].value == "" || theForm.yourName.value == "" || theForm.yourEmail.value == "" || theForm.subject.value == "" || theForm.message.value == "" || theForm.code.value == "") {
				errors = true;
				alert("Please fill in all required fields.");
			}
			if(!isValidEmail(theForm.yourEmail.value)) {
				errors = true;
				alert("Please use a valid email address.");
			}
			if(errors == false) {
				theForm.setStyles({opacity:0});
				$('contactEmailFormBox').addClass('loading');
				theForm.set('send', {
					onComplete: function(txt) {
						if(txt == "code invalid") {
							alert("The NO-SPAM Verification Code is incorrect. Please re-enter it.");
						}
						else {
							alert(txt);
							theForm.to.options[0].selected = true;
							theForm.yourName.value = "";
							theForm.yourEmail.value = "";
							theForm.subject.value = "";
							theForm.message.value = "";
							theForm.code.value = "";
							//RELOAD NEW SECURE IMAGE
							$('image').src = '/secureimage/securimage_show.php?sid=' + Math.random();
						}
						theForm.setStyles({opacity:1});
						$('contactEmailFormBox').removeClass('loading');
					},
					onFailure: function() {
						alert('Sorry! The network was busy. Please try again later.');
						theForm.setStyles({opacity:1});
						$('contactEmailFormBox').removeClass('loading');
					}
				}).send();
			}
		});
	}
}







//////////////////////////////////
// PLEDGE FORM STUFF    //////////
//////////////////////////////////
function initPledgeForm() {
	
	if($('pledgeForm')) {
		
		var errors = false;
		
		//PRAYER REQUEST FORM
		var theForm = $('pledgeForm');
		theForm.addEvent('submit', function(e) {
			e.stop();
			errors = false;
			if(theForm.firstName.value == "") {
				errors = true;
				alert("Please fill in all required fields.");
			}
			if(!isValidEmail(theForm.email.value)) {
				errors = true;
				alert("Please use a valid email address.");
			}
			if(errors == false) {
				theForm.setStyles({opacity:0});
				$('pledgeFormBox').addClass('loading');
				theForm.set('send', {
					onComplete: function(txt) {
						if(txt == "code invalid") {
							alert("The NO-SPAM Verification Code is incorrect. Please re-enter it.");
						}
						else {
							theForm.empty();
							theForm.set('html',txt);
						}
						theForm.setStyles({opacity:1});
						$('pledgeFormBox').removeClass('loading');
					},
					onFailure: function() {
						alert('Sorry! The network was busy. Please try again later.');
						theForm.setStyles({opacity:1});
						$('pledgeFormBox').removeClass('loading');
					}
				}).send();
			}
		});
	}
}

function validateEventSubmit(theForm) {
	var reason = "";
	reason += validateEmpty(theForm.catID,"Event Type");
	reason += validateEmpty(theForm.title,"Event");
	reason += validateEmpty(theForm.content,"Description");
	reason += validateEmpty(theForm.startdate,"Start Date");
	reason += validateEmpty(theForm.time,"Time");
	reason += validateEmpty(theForm.place,"Place");
	reason += validateEmpty(theForm.city,"City");
	reason += validateEmpty(theForm.yourname,"Your Name");
	reason += validateEmpty(theForm.youremail,"Your Email");
	reason += validateEmpty(theForm.yourphone,"Your Phone");
      
	if(reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}
	return true;
}

function validateStorySubmit(theForm) {
	var reason = "";
	reason += validateEmpty(theForm.title,"Story Title");
	reason += validateEmpty(theForm.content,"Description");
	reason += validateEmpty(theForm.yourname,"Your Name");
	reason += validateEmpty(theForm.youremail,"Your Email");
	reason += validateEmpty(theForm.yourphone,"Your Phone");
	reason += validateEmpty(theForm.code,"NO-SPAM Validation");
      
	if(reason != "") {
		alert("Some fields need correction:\n" + reason);
		return false;
	}
	return true;
}




///////////////////////////////////////////////////
// GENERAL PURPOSE           //////////////////////
///////////////////////////////////////////////////
function notEmpty(fld) {
	var error = false;
	if(fld.get('tag') == "input" && fld.get('type') == "text" && fld.value.length == 0) error = true;
	else if(fld.get('tag') == "input" && fld.get('type') == "checkbox" && fld.checked == false) error = true;
	else if(fld.get('tag') == "textarea" && fld.value.length == 0) error = true;
	else if(fld.get('tag') == "select" && fld.options[fld.selectedIndex].value == "") error = true;
	return (error == false) ? true: false;  
}


function validateEmpty(fld,alerttxt) {
    var error = "";
    if (fld.value.length == 0) {
        fld.style.background = '#fff999'; 
        error = alerttxt+"\n";
    } 
    else { fld.style.background = '#ffffff url(/images/inputbg.gif) top left no-repeat'; }
    return error;  
}
function isValidEmail(str) {
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}


///////////////////////////////////////////////////
// URL ENCODING FOR AJAX     //////////////////////
///////////////////////////////////////////////////
var Url = {

	encode : function (string) { return escape(this._utf8_encode(string)); },
	decode : function (string) { return this._utf8_decode(unescape(string)); },
	
	_utf8_encode : function (string) {
	  	string = string.replace(/\r\n/g,"\n");
	 	var utftext = "";
	  	for (var n = 0; n < string.length; n++) {
	   		var c = string.charCodeAt(n);
	   		if (c < 128) {
	    			utftext += String.fromCharCode(c);
	 		} 
	 		else if((c > 127) && (c < 2048)) {
	  			utftext += String.fromCharCode((c >> 6) | 192);
	  			utftext += String.fromCharCode((c & 63) | 128);
	 		} 
	 		else {
	  			utftext += String.fromCharCode((c >> 12) | 224);
	  			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
	 	 		utftext += String.fromCharCode((c & 63) | 128);
	 		}
	 	}
		return utftext;
	},
	
	_utf8_decode : function (utftext) {
	 	var string = "";
	 	var i = 0;
	 	var c = c1 = c2 = 0;
	  	while ( i < utftext.length ) {
	  		c = utftext.charCodeAt(i);
	   		if (c < 128) {
	    		string += String.fromCharCode(c);
	    		i++;
	  		} 
	  		else if((c > 191) && (c < 224)) {
	 			c2 = utftext.charCodeAt(i+1);
	    		string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	    		i += 2;
	  		} 
	  		else {
	 			c2 = utftext.charCodeAt(i+1);
	    		c3 = utftext.charCodeAt(i+2);
	    		string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	   			i += 3;
	 		}
		}
		return string;
	}
}





