

window.addEvent('domready', function(){
	initPrayerButtons();
	initNav();
	initSeagull();
	moveLeftPincher();
	moveRightPincher();
	initFlipFlops();
	initCalCatNav();
	initPrayerForms();
	initAdvertiserForm();
	setTimeout(function () { resizePageContainers(); }, 1000);
	$(window).addEvent('resize', function(){ resizePageContainers(); });
	initRotator();
});

swfobject.embedSWF('/flash/cloud.swf', 'flashbg', '100%', '50%', '10.0.2', '/flash/expressInstall.swf', 
	//FLASHVARS
	{},
	//PARAMS
	{allowscriptaccess: 'always', bgcolor: '#000000', menu: 'false', wmode: 'transparent'}, 
	//ATTRIBUTES
	{id: 'flashbg1'}
);


function popUpPlayer() {
	window.open("http://www.streamaudio.com/player/player.aspx?optin=no&station=WSRX_FM", "popUpPlayer", "location=0,status=0,scrollbars=0,width=646,height=371");
}



function resizePageContainers() {
	if($(window).getSize().y >= $('container').getSize().y) {
		var minHeight = 400;
		var yardStick = $(window).getSize().y;
		yardStick = (yardStick < minHeight) ? minHeight: yardStick;
		
		//RESIZE MAIN CONTAINERS
		$('beachocean').setStyles({'height':yardStick, 'min-height':$(window).getSize().y});
		$('container').setStyles({'height':yardStick, 'min-height':$(window).getSize().y});
		//RESIZE CONTENT AREA
		var theDiff = $('container').getSize().y - ($('header').getSize().y + $('footer').getSize().y);
		$('content').setStyle('height',theDiff);
	}
}


function initAdvertiserForm() {

	if($('advertiseForm')) {
		
		var errors = false;
		
		//PRAYER REQUEST FORM
		var theForm = $('advertiseForm');
		theForm.addEvent('submit', function(e) {

			e.stop();
			errors = false;
			if(theForm.contactEmail.value == "") {
				errors = true;
				alert("Please fill in all required fields.");
			}
			if(theForm.contactEmail.value != "" && !isValidEmail(theForm.contactEmail.value)) {
				errors = true;
				alert("Please use a valid email address.");
			}

			if(errors == false) {
				theForm.setStyles({opacity:0});
				$('advertiseFormBox').addClass('loading');
				theForm.set('send', {
					onComplete: function(txt) {
						if(String.from(txt).trim() == "code invalid") {
							alert('The SPAM Guard code was incorrect. Please re-type it.');
							theForm.setStyles({opacity:1});
							$('advertiseFormBox').removeClass('loading');
							theForm.code.value = "";
						}
						else {
							theForm.empty();
							theForm.set('html',txt);
							theForm.setStyles({opacity:1});
							$('advertiseFormBox').removeClass('loading');
						}
					},
					onFailure: function() {
						alert('Sorry! The network was busy. Please try again later.');
						theForm.setStyles({opacity:1});
						$('advertiseFormBox').removeClass('loading');
					}
				}).send();
			}
		});
	}
}




////////////////////////////
// PRAYERS          ////////
////////////////////////////
function initPrayerButtons() {
	var box = new CeraBox();
	if($('requestButton')) {
		box.addItems('#requestButton', {
			displayTitle: false,
			animation: 'ease',
			ajax: {
				type: 'post',
				data: 'pType=getPrayerForm'
			},
			events: {
				onOpen: function(ee, cc) {
					initPrayer();
				}
			}
		});
	}
	if($('prayerListings')) {
		box.addItems('#prayerListings .sendNoteButton', {
			displayTitle: false,
			animation: 'ease',
			group: false,
			ajax: {
				type: 'post'
			},
			events: {
				onOpen: function(ee, cc) {
					initPrayerNote();
				}
			}
		});
	}
}


function initPrayer() {
	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(prayerForm.email.value != "" && !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();
					alert("Thank you!");

					var newPrayer = new Element('div');
					newPrayer.set('html',txt);
					newPrayer.inject($('prayerListings'),'top');
					
					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();
		}
	});
}
function initPrayerNote() {
	var prayerForm = $('messageForm');
	prayerForm.addEvent('submit', function(e) {
		e.stop();
		errors = false;
		if(prayerForm.content.value == "" || prayerForm.email.value == "") {
			errors = true;
			alert("Please fill in all required fields.");
		}
		if(prayerForm.email.value != "" && !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) {
					alert("Thank you!");
					prayerForm.empty();
					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();
		}
	});
}


function flagThisPrayer(ID) {
	if(confirm('Flagging a request alerts the website administrator.\nIf they judge the request to be inappropriate, it will be deleted.\n\nWould you like to flag this request?')) {
		var req = new Request({ url:'/includes/processPrayer.php', method:'get', data:"pType=flagPrayer&ID="+ID, urlEncoded:true, evalScripts:true,
			onSuccess: function(txt) {
				alert(txt);
				$('item'+ID).destroy();
			},
			onFailure: function() {}
		}).send();
	}
}
function starThisPrayer(ID) {
	var req = new Request({ url:'/includes/processPrayer.php', method:'get', data:"pType=starPrayer&ID="+ID, urlEncoded:true, evalScripts:true,
		onSuccess: function() {
			var newStar = new Element('img', {src:'/images/prayerstar.gif'});
			newStar.inject($('stars'+ID),'top');
			$('starButton'+ID).destroy();
		},
		onFailure: function() {}
	}).send();
}




////////////////////////////
// SEAGULL          ////////
////////////////////////////
var beakState = "top";
var beakTimeout;
function initSeagull() {
	$('verseBox').setStyles({'opacity':0,'display':'block'});
	$('seagull').addEvent('mouseover', function(){ 
		toggleVerseBox("on");		
	});
	$('seagull').addEvent('mouseout', function(){
		toggleVerseBox("off");	
	});
}

function toggleVerseBox(state) {
	if(state == "on") {
		moveBeak();
		verseBoxFade(1);
		crabFade("in");
	}
	else {
		clearTimeout(beakTimeout);
		$('seagull').setStyle('background-position','top left');
		verseBoxFade(0);
		crabFade("out");
	}
}
function moveBeak() {
	var theTime = Number.random(50, 250);
	beakTimeout = setTimeout(function () { 
		$('seagull').setStyle('background-position',beakState+' left');
		beakState = (beakState == "top") ? "bottom": "top";
		moveBeak();
	}, theTime);
}
function verseBoxFade(state) {
	var blackOut = new Fx.Morph($('verseBox'), {duration:0, duration:200,transition: Fx.Transitions.Cubic.easeOut, wait:false}).start({'opacity':state});
}




////////////////////////////
// CRAB             ////////
////////////////////////////
var pLeftState = "top";
var pLeftTimeout;
var pRightState = "top";
var pRightTimeout;

function moveLeftPincher() {
	pLeftTimeout = setTimeout(function () { 
		$('crabPincherLeft').setStyle('background-position',pLeftState+' left');
		pLeftState = (pLeftState == "top") ? "bottom": "top";
		moveLeftPincher();
	}, Number.random(100, 450));
}
function moveRightPincher() {
	pRightTimeout = setTimeout(function () { 
		$('crabPincherRight').setStyle('background-position',pRightState+' left');
		pRightState = (pRightState == "top") ? "bottom": "top";
		moveRightPincher();
	}, Number.random(100, 450));
}
function crabFade(state) {
	var top = (state == "in") ? 8: 60;
	var right = (state == "in") ? 50: 200;
	var crabMove = new Fx.Morph($('crab'), {duration:0, duration:300,transition: Fx.Transitions.Cubic.easeOut, wait:false}).start({'right':right,'top':top});
}





////////////////////////////
// FLIP FLOPS       ////////
////////////////////////////
function initFlipFlops() {
	if($('factBox')) {
		$('factBox').setStyles({'opacity':0,'display':'block'});
		$('flipFlops').addEvent('mouseover', function() { 
			factFade(1);		
		});
		$('flipFlops').addEvent('mouseout', function() {
			factFade(0);	
		});
	}
}

function factFade(state) {
	var blackOut = new Fx.Morph($('factBox'), {duration:0, duration:200,transition: Fx.Transitions.Cubic.easeOut, wait:false}).start({'opacity':state});
}



/*
FEEDBACK FORM - DEPRECATED
function initFeedbackForm() {

	if($('feedbackForm')) {
		
		var errors = false;
		
		//PRAYER REQUEST FORM
		var theForm = $('feedbackForm');
		theForm.addEvent('submit', function(e) {

			e.stop();
			errors = false;
			if(theForm.name.value == "" || theForm.message.value == "" || theForm.email.value == "" || theForm.code.value == "") {
				errors = true;
				alert("Please fill in all required fields.");
			}
			if(theForm.email.value != "" && !isValidEmail(theForm.email.value)) {
				errors = true;
				alert("Please use a valid email address.");
			}

			if(errors == false) {
				theForm.setStyles({opacity:0});
				$('feedbackBoxInside').addClass('loading');
				theForm.set('send', {
					onComplete: function(txt) {
						if(String.from(txt).trim() == "code invalid") {
							alert('The SPAM Guard code was incorrect. Please re-type it.');
							theForm.setStyles({opacity:1});
							$('feedbackBoxInside').removeClass('loading');
							theForm.code.value = "";
						}
						else {
							theForm.empty();
							theForm.set('html',txt);
							theForm.setStyles({opacity:1});
							$('feedbackBoxInside').removeClass('loading');
						}
					},
					onFailure: function() {
						alert('Sorry! The network was busy. Please try again later.');
						theForm.setStyles({opacity:1});
						$('feedbackBoxInside').removeClass('loading');
					}
				}).send();
			}
		});
	}
}
*/












/////////////////////////////////
// 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();
	*/
}



/////////////////////////////////
// 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()-$('nav').getLeft(): link.getLeft()-$('nav').getLeft();
	var dropTop = link.getTop()+32;
	//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':dropTop,'left':dropLeft,'z-index':'10000'}): dropBox.setStyles({'opacity':0,'display':'none'});
	//if(state == "over") blackOut.start({opacity: 1});
}











//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});
		});
	}
}


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();
		});
	}
}












//////////////////////////////////
// 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;
	}
	if(!isValidEmail(theForm.youremail.value)) {
		alert("Please provide a valid Email Address");
		return false;
	}
	return true;
}


function validateStorySubmit(theForm) {
	var errors = false;
	
	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);
		errors = true;
	}
	if(!isValidEmail(theForm.email.value)) {
		alert("Please provide a valid Email Address");
		errors = true;
	}
	return (errors == false) ? true: false;
}




///////////////////////////////////////////////////
// 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) {
	var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	return (str.search(emailRegEx) == -1) ? false: true;
}


///////////////////////////////////////////////////
// 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;
	}
}





