var ajaxObjects=new Array();
var moLen=new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
var moStartArray=new Array(1,1,4,4,0,2,5,0,3,6,1,4,6);
var amatrix=[0,.016,.047,.094,.156,.234,.328,.438,.563,.672,.766,.844,.906,.953,.984,1];
var moCurr=5;
var yrCurr=2009;
var summary_limit=80; // summary container height in pixels
var change_flag=false;
var pageInitialized=false;
var weekSelected='';
var rowDate;

/* Player
****************************/

var player = null;
var creatingPlayer=false;
var currentState,previousState;
var fromOtherLink=false;
var nowPlaying='';
var playerCreated=false;

function playerReady(thePlayer) {
	if(playerCreated) return false;
	player=window.document[thePlayer.id];
	addListeners();
}

function addListeners() {
	if(player) { 
		player.addModelListener("STATE", "stateListener");
		player.addControllerListener("STOP","playerStopped");
		playerCreated=true;
	} else {
		setTimeout("addListeners()",500);
	}
}

function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate; 
	previousState = obj.oldstate;
//	$('stat').innerHTML='s previous:'+previousState+'<br>s current:'+currentState;
}

function playerStopped(obj){
	var tt=new Date().getTime();
//	$('debug').innerHTML=tt+'<br>previous:'+previousState+'<br>current:'+currentState;
	if(previousState!='IDLE' && currentState=='IDLE' && !fromOtherLink){
		$('player_div').style.bottom='-100px';
		for(i=0;i<7;i++){
			classRem($('weekrow'+i),'current');
		}
		nowPlaying='';
	}
}

function createPlayer() {
	var flashvars = {
		type:"sound",
		icons:"false",
		height: "45",
		playlist: "none",
		playlistsize: "0",
		skin:"swf/skin.swf",
		autostart:"false"
	}

	var params = {
		allowfullscreen:"true", 
		allowscriptaccess:"always"
	}

	var attributes = {
		id:"player1",  
		name:"player1"
	}
	swfobject.embedSWF("/taglib/swf/player.swf", "audio_player", "100%", "45", "9.0.115", false, flashvars, params, attributes);
}

function mp3play(fname,titl,duration,rowid){
	for(i=0;i<7;i++){
		classRem($('weekrow'+i),'current')
	}
	classAdd($('weekrow'+rowid),'current');
	nowPlaying=fname;
	$('audio_title').innerHTML=titl+'<a href="javascript:mp3stop()"><img src="/images/main/bg-audio_close.png" alt="close" /></a>';
	$('player_div').style.bottom='0px';
	fromOtherLink=true;
	
  player.sendEvent('STOP');
  player.sendEvent('LOAD',{file:'/audio/'+fname,duration:duration})
 	player.sendEvent('PLAY',"true");
  fromOtherLink=false;
}

function mp3stop(){
	player.sendEvent('STOP');
}

/* Calendar Navigation
****************************/

var date_presel='';
function monthSel(mo,yr){
	if(document.cookie.search(/datetmp=(\d+)/)>=0){
		date_presel=RegExp.$1;
		if(date_presel.search(/^(\d{4})(\d{2})/)==0){
			yr=RegExp.$1;
			mo=RegExp.$2;
			mo=mo*1;
		}
	}
	if(change_flag)return false;
	moCurr=parseInt(mo);
	yrCurr=parseInt(yr);
	$('selMo').selectedIndex=mo-1;
	var prevMonth=monthAdd(mo,yr,-1);
	var nextMonth=monthAdd(mo,yr,1);
	var prevMonthInfo=getMonthInfo(prevMonth.mo,prevMonth.yr);
	var thisMonthInfo=getMonthInfo(mo,yr);
	var nextMonthInfo=getMonthInfo(nextMonth.mo,nextMonth.yr);

	lentmp=$('month_rows').rows.length;
	for(i=0;i<lentmp;i++){
		$('month_rows').deleteRow(0);
	}
	var wDay=thisMonthInfo.start;
	var newrow=document.createElement('TR');
	newrow.onclick=function(){weekSel();};

	// previous month end
	for(i=0;i<thisMonthInfo.start;i++){
		if(i==0){
			rowDate=prevMonth.yr.toString()+printf('%02d',prevMonth.mo)+(prevMonthInfo.len-thisMonthInfo.start+1).toString();
			newrow.id='row'+rowDate;
			if(newrow.id==weekSelected) newrow.className='week_current';
		}
		var newcell=document.createElement('TD');
		newcell.className='last_month';
		var num=prevMonthInfo.len-thisMonthInfo.start+i+1
		//newcell.innerHTML='<a href="'+rowDate+'">'+num+'</a>';
		newcell.innerHTML=num;
		newrow.appendChild(newcell);
	}

	// current month
	for(i=1;i<=thisMonthInfo.len;i++){
		if(wDay==0){
			rowDate=yrCurr.toString()+printf('%02d',moCurr)+printf('%02d',i);
			newrow.id='row'+rowDate;
			if(newrow.id==weekSelected) newrow.className='week_current';
		}
		var newcell=document.createElement('TD');
		//newcell.innerHTML='<a href="'+rowDate+'">'+i+'</a>';
		newcell.innerHTML=i;
		if(mo==nowMo && yr==nowYr && i==nowDa){
			if(!pageInitialized){
				weekSelected=newrow.id;
				pageInitialized=true;
			}
			newcell.className='today';
		}

		newrow.appendChild(newcell);
		wDay++;
		if(wDay>6){
			wDay=0;
			$('month_rows').appendChild(newrow);
			newrow=document.createElement('TR');
			newrow.onclick=function(){weekSel();};
		}
	}

	// next month
	if(wDay>0){
		for(i=wDay;i<7;i++){
			var newcell=document.createElement('TD');
			newcell.className='next_month';
			//newcell.innerHTML='<a href="'+rowDate+'">'+(i-wDay+1)+'</a>';
			newcell.innerHTML=(i-wDay+1);
			newrow.appendChild(newcell);
		}
	}
	$('month_rows').appendChild(newrow);
	
	// populate year drop-down +-5
	change_flag=true;
	seltop=$('selYr').options.length;
	for(i=0;i<seltop;i++){
		$('selYr').remove(0);
	}
	for(i=yrCurr-5;i<yrCurr+6;i++){
		var optNew=document.createElement('OPTION');
		optNew.text=i;
		optNew.value=i;
		try {
	    $('selYr').add(optNew, null); // standards compliant; doesn't work in IE
	  }
	  catch(ex) {
	    $('selYr').add(optNew); // IE only
	  }
	}
	$('selYr').selectedIndex=5;
	change_flag=false;
	if(navtoWeekstart){
		weekSel('row'+navtoWeekstart);
	}
}

function getMonthInfo(mo,yr){
  var moStart=moStartArray[mo]+Math.floor((yr-1)*1.25);
  var len=moLen[mo];
  if(yr/4==Math.floor(yr/4)){
    if(mo>2) moStart++;
    if(mo==2) len=29;
  }
  moStart+=6;
  moStart=moStart % 7;
	return {len:len, start:moStart};
}

function monthAdd(mo,yr,inc){
	mOut=parseInt(mo)+inc;
	yOut=parseInt(yr);
	if(mOut==13){
		mOut=1;
		yOut++;
	}
	if(mOut==0){
		mOut=12;
		yOut--;
	}
	return {mo:mOut,yr:yOut};
}

function monthNext(){
	var info=monthAdd(moCurr,yrCurr,1);
	monthSel(info.mo,info.yr);
}

function monthPrev(){
	var info=monthAdd(moCurr,yrCurr,-1);
	monthSel(info.mo,info.yr);
}

/* Week Selection
****************************/

function weekSel(){
	if(arguments.length){
		raw=arguments[0];
	}else{
		var ev = window.event||arguments.callee.caller.arguments[0];
		var srcElem=ev.target||ev.srcElement;
		if(srcElem.tagName=='A') srcElem=srcElem.parentNode;
		if(srcElem.tagName=='TD') srcElem=srcElem.parentNode;
		raw=srcElem.id;
	}
	for(i=0;i<$('month_rows').rows.length;i++){
		$('month_rows').rows[i].className='';
	}
	if(raw.search(/row(\d+)/)>=0){
		$(raw).className='week_current';
		weekSelected=raw;
		strDate=RegExp.$1;
		var ajaxIndex=ajaxObjects.length;
		ajaxObjects[ajaxIndex]=new sack();
		with(ajaxObjects[ajaxIndex]){
			requestFile ="/cgi-bin/ttb.cgi";
			setVar('action','week_pick');
			setVar('date',strDate);
			onCompletion=function(){weekSelResponse(ajaxIndex);};
			runAJAX();
		}
	}
}

function weekInc(daterowid,sType){
	if(!$(daterowid)){
		if(sType=='next'){
			monthNext();
		}else{
			monthPrev();
		}
	}
	weekSel(daterowid);
}

function weekSelResponse(index){
	txt=ajaxObjects[index].response;
	txt=unescape(txt);
	$('week').innerHTML=txt;
	// fix oversized summaries
	pscan=$('week').getElementsByTagName('P');
	for(i=0;i<pscan.length;i++){
		if(pscan[i].className=='summary'){
			if(pscan[i].offsetHeight>summary_limit){
				cont=pscan[i].parentNode;
				var morelink=document.createElement('DIV');
				morelink.className='read_more';
				morelink.innerHTML='<a href="javascript:void(0)" onclick="summaryShow(this)">'+show_more+' &raquo;</a>';
				cont.appendChild(morelink);
			}
		}
	}
	
	// called from URL - play item
	var itemtmp=getCookie('itemtmp');
	if(navtoIndex.toString()>'')itemtmp=navtoIndex.toString();
	if(itemtmp=='null')itemtmp='';
	
	if(itemtmp>''){
		// play selected item, clear out presel cookies
		srcrow=$('weekrow'+itemtmp);
		tmpdata=srcrow.innerHTML;
		if(tmpdata.search(/javascript:mp3play\((.*?)\)\"/g)>0){
			var presel_params=RegExp.$1;
			eval("mp3play("+presel_params+")");
		}
		document.cookie='datetmp=; path=/;';
		document.cookie='itemtmp=; path=/;';
		navtoIndex='';
		navtoWeekstart='';
		date_presel='';
		tmp=scrollVisible(srcrow,50);
	}
	if(nowPlaying=='') return false;
	for(i=0;i<7;i++){
		obj=$('weekrow'+i);
		if(obj.innerHTML.indexOf("'"+nowPlaying+"'")>0){
			classAdd(obj,'current');
			break;
		}
	}
}

function dateDblClick(){
	var ev=window.event||arguments.callee.caller.arguments[0];
	var srcElem=ev.target||ev.srcElement;
	if(srcElem.tagName!='TD') return false;
	navtoIndex=srcElem.cellIndex;
}

/* Summary expand/collapse
****************************/

var heightStart, heightDelta, heightIndex, objExpand, objExpandLink;

function summaryShow(obj){
	objExpand=obj.parentNode.parentNode;
	objExpandLink=obj.parentNode;
	objExpandLink.innerHTML='<a href="javascript:void(0)" onclick="summaryHide(this)">'+show_less+' &laquo;</a>';
	var pToShow=objExpand.getElementsByTagName('P')[0];
	var heightEnd=pToShow.offsetHeight+30;
	heightStart=summary_limit;
	objExpand.style.height=heightStart;
	classAdd(objExpand,'active');
	heightDelta=heightEnd-heightStart;
	heightIndex=0;
	heightInc();
}

function summaryHide(obj){
	objExpand=obj.parentNode.parentNode;
	objExpandLink=obj.parentNode;
	objExpandLink.innerHTML='<a href="javascript:void(0)" onclick="summaryShow(this)">'+show_more+' &raquo;</a>';
	var pToShow=objExpand.getElementsByTagName('P')[0];
	var heightEnd=summary_limit;
	heightStart=objExpand.offsetHeight;
	objExpand.style.height=heightStart;
	classAdd(objExpand,'active');
	heightDelta=heightEnd-heightStart;
	heightIndex=0;
	heightInc();
}

function heightInc(){
	heightIndex++;
	if(heightIndex>=amatrix.length){
		if(heightDelta<0){
			classRem(objExpand,'active');
		}
		return false;
	}
	var curHeight=heightStart+Math.round(heightDelta*amatrix[heightIndex]);
	objExpand.style.height=curHeight+'px';
	setTimeout('heightInc()',20);
}

/* Passage expand/collapse
****************************/

var pheightIndex, pheightStart, pheightDelta;
function showPassage(which){
	curHeight=$('passage'+which).offsetHeight;
	if(curHeight>0){
		pheightStart=$('passage'+which).childNodes[0].offsetHeight+10;
		pheightDelta=pheightStart*-1;
	}else{
		pheightStart=0;
		pheightDelta=$('passage'+which).childNodes[0].offsetHeight+10;
	}
	pheightIndex=0;
	pheightInc(which);
}

function pheightInc(which){
	pheightIndex++;
	if(pheightIndex>=amatrix.length){
		return false;
	}
	var curHeight=pheightStart+Math.round(pheightDelta*amatrix[pheightIndex]);
	$('passage'+which).style.height=curHeight+'px';
	setTimeout('pheightInc('+which+')',20);
}

/* Scripture references
****************************/

function refSearch(){
	strBook=($('book').value.split('|'))[0];
	strChapt=$('chapter').value;
	var ajaxIndex=ajaxObjects.length;
	ajaxObjects[ajaxIndex]=new sack();
	with(ajaxObjects[ajaxIndex]){
		requestFile ="/cgi-bin/ttb.cgi";
		setVar('action','search');
		setVar('book_id',strBook);
		setVar('chapter',strChapt);
		onCompletion=function(){refSearchResponse(ajaxIndex);};
		runAJAX();
	}
}

function refSearchResponse(index){
	txt=ajaxObjects[index].response;
	$('search_results').innerHTML=txt;
}

var navtoWeekstart='';
var navtoIndex='';
function navTo(weekstart,index){
	navtoWeekstart=weekstart;
	navtoIndex=index;
	//$('debug').innerHTML=navtoWeekstart+', '+navtoIndex;
	if(weekstart.search(/^(\d{4})(\d{2})/)==0){
		yr=RegExp.$1;
		mo=RegExp.$2;
		monthSel(mo*1,yr);
	}
}

function chapterPop(){
	str=$('book').value.search(/\|(\d+)$/);
	chapters=RegExp.$1;
	var oSelect=$('chapter');
	for(i=oSelect.options.length-1;i>=0;i--){
		oSelect.options[i]=null;
	}
	optNew=document.createElement('OPTION');
	optNew.innerHTML='&hellip;';
	optNew.value='';
	oSelect.options.add(optNew);
	for(i=1;i<=chapters;i++){
		optNew=document.createElement('OPTION');
		oSelect.options.add(optNew);
		optNew.innerHTML=i;
		optNew.value=i;
	}
}

/* Share
****************************/

function media_share(vurl,obj){
	// get all params
	listen_tag=obj.parentNode.getElementsByTagName('A')[0].href.toString();
	var mp3url, entry_title;
	if(listen_tag.search(/mp3play\('(.*?)','(.*?)'.*?\)/)>0){
		mp3url=RegExp.$1;
		entry_title=unescape(RegExp.$2);
	}
	
	pos=getObjPos(obj);
	$('share').style.top=(pos.y-70)+'px';
	$('share').style.left=(pos.x-170)+'px';
	mainurl=window.location.href+vurl;
	$('share_url').value=mainurl;
	$('share_link').value='<a href="'+mainurl+'">'+entry_title+'</a>';
	var ecode='<embed type="application/x-shockwave-flash" src="'+window.location.href+'swf/mp3_embed.swf" id="ttbPlayer" name="ttbPlayer" bgcolor="#FFFFFF" quality="high" allowfullscreen="true" flashvars="string='+entry_title+'&amp;seriesLink='+mainurl+'&amp;song='+window.location.href+'/audio/'+mp3url+'&src='+window.location.href+'swf/mp3_embed.swf" width="320" height="218">';
	$('share_embed').value=ecode;
	$('share').style.display='block';
}

function shareClose(){
	$('share').style.display='none';
}

/* Misc
****************************/

function languageSel(){
	var selid=(arguments.length>0?arguments[0]:'language_id');
	l_id=$(selid).value;
	//document.cookie='language_id='+l_id+'; expires=Fri, 01-May-2099 00:00:01 GMT; path=/;'
	document.cookie='language_id='+l_id+'; path=/;'
	window.location.reload();
}

function presel(){
	cmp='row'+date_presel;
	mrows=$('month_rows').rows;
	var weekpresel='';
	for(i=0;i<mrows.length;i++){
		if(cmp<mrows[i].id){
			tgt=i-1;
			if(tgt<0)tgt==0;
			weekpresel=mrows[tgt].id;
			break;
		}
	}
	if(i==mrows.length){
		weekpresel=mrows[i-1].id;
	}
	if(weekpresel>'') weekSel(weekpresel);
}

function calInit(){
	createPlayer();
	if(date_presel>''){
		//presel();
		weekSel('row'+date_presel);
	}else if(weekSelected>''){
		weekSel(weekSelected);
	}
}

addEvent(window,'load',calInit,false);