var sections          =  null;
var loading           = false;
var direction         =     0;
var first_section_id  =     1;
var last_section_id   =     1;
var first_line_no     =     [-1];
var last_line_no      =     [-1];
var first_word_no     =     -1;
var last_word_no      =     -1;
var old_first_section_id = -1;
var old_first_line_no = [-1];
var old_first_word_no = -1;
var current_list_type =  null;
var current_list_id   =  null;
var content_left_html =    "";
var content_right_html =   "";
var previous_direction = 0;
var show_spinner = false;
var end_of_page = false;
var moving_cursor = false;
var moving_cursor_object = null;
var background_load = false; //This toggles wehter getMoreSections renders or just tacks on
var _replaceContext = false;
var mouseX = 0;
var mouseY = 0;
var page_cache=false;
var beta_mode = true; //Set to false after beta is over
var render_benchmarks = new Object();
var ajax_loading = false;
var load_spinner_visible=false;

/*******************************
Function: initBibleView
Description: initializes bible javascript
with data given by rails view at load
********************************/
function initBibleView(ifirst_section_id,ifirst_line_no,ifirst_word_no,itranslation_id,icurrent_list_type,icurrent_list_id,search_bcv,search_end_bcv,isections)
{
	first_section_id    =  ifirst_section_id;
	first_line_no       =     ifirst_line_no;
	first_word_no       =     ifirst_word_no;
	translation_id      =    itranslation_id;
	current_list_type   = icurrent_list_type;
	current_list_id     =   icurrent_list_id;
	sections            =          isections;
	highlight_start		=         search_bcv;
	if(search_end_bcv == "0")
	{
		highlight_end		= 		  search_bcv;
	}
	else
	{
		highlight_end		= 		  search_end_bcv;
	}
	// highlight_start		= "1.1.1";
	// highlight_end		="1.2.1";
	//Add Code to add event handlers to left and right page buttons
	
	//Fire render of page
	renderPageForward();
}
Event.observe(window, 'load', function() {
    setTimeout("updateLoading()","100");
	$('bible_previous_page').observe('click', function(event) {
		getPreviousSections(event);

	});
	$('bible_next_page').observe('click', function(event) {
		getNextSections(event);
	});
	document.onkeydown = bibleKeyListener;
});

function updateLoading()
{
    if(loading && show_spinner == true && load_spinner_visible == false)
    {
        var bible_spinner = $('bible_loading');
        bible_spinner.setStyle({left: '305px'});
		bible_spinner.show();
		load_spinner_visible=true;
    }
    if(!loading && load_spinner_visible == true)
    {
        var bible_spinner = $('bible_loading');
        bible_spinner.setStyle({left: '-5000px'});
		bible_spinner.hide();
		load_spinner_visible=false;
		show_spinner = false;
    }
    setTimeout("updateLoading()","100");
}

function bibleKeyListener(e){
	if(object_focused)
	{
		return;
	}
   if(!e){
      //for IE
      e = window.event;
   }
   if(e.keyCode==37){
      //keyCode 37 is left arrow
      getPreviousSections(null);
   }
   if(e.keyCode==39){
      getNextSections(null)
   }
   // FYI - keyCode 38 is up arrow, 
   //       keyCode 40 is down arrow
}
function resizeBible()
{
	if(direction == 0)
	{
		renderPageForward();
	}
	else
	{
		renderPageReverse();
	}
}
function goToVerse(range)
{
	var bcvs = range.split('-');
    var bcv_start = bcvs[0];
	var bcv_end = bcvs[0];
	if(bcvs.length >1)
	{
		bcv_end = bcvs[1];
	}

	var bcv_split = bcv_start.split('.')
	first_line_no = [-1];
	first_word_no = -1;
	first_section_id = 1;
	loading=true;
	direction=0;
	j1w_ajaxAction('/section/verse?translation_id=' + translation_id + '&book=' + bcv_split[0] + '&chapter=' + bcv_split[1] + '&verse=' + bcv_split[2],'',getSectionsResponse);
}
function getMoreSections()
{
	if(ajax_loading == true)
	{
		setTimeout("getMoreSections()","200")
	}
	loading = true;
	ajax_loading = true;
	if(direction == 0)
	{
		
		j1w_ajaxAction('/section/next?translation_id=' + translation_id + '&first_section_id=' + (sections[sections.length-1].section.section_number + 1) + '&first_line_no=' + first_line_no[0] + '&first_word_no=' + first_word_no,'',getMoreSectionsResponse);
	}
	else
	{
		if(sections[sections.length-1].section.section_number <= 1)
		{
			first_section_id = 0;
			first_line_no = [-1];
			first_word_no = -1;
			direction = 0;
			previous_direction = 0;
			loading = false;
			ajax_loading = false;
			getSections(null);
		//	loading = false;
		//	ajax_loading = false;
		}
		else
		{
			j1w_ajaxAction('/section/prev?translation_id=' + translation_id + '&last_section_id=' + (sections[sections.length-1].section.section_number - 1)  + '&first_line_no=' + first_line_no[0] + '&first_word_no=' + first_word_no,'',getMoreSectionsResponse);			
		}

	}
}

function getMoreSectionsResponse(response)
{
	new_sections = eval('(' + response.responseText + ')');
	if (new_sections.length == 0) {
	    ajax_loading = false;;loading = false;processContent();
	    if(last_word_no == -1 && last_section_id >= sections[sections.length-1].section.section_number) {
	        end_of_page = true;
	    }
	    return;
	} // stop processing
	
	sections = sections.concat(new_sections);
	if(background_load)
	{
		background_load = false;
		loading  = false;
		ajax_loading = false;
		return;
	}
	else
	{
		loading  = false;
		ajax_loading = false;
		direction == 0 ? renderPageForward() : renderPageReverse();
	}

}
function getSections(event)
{
	var currdate = new Date();
	render_benchmarks.ajax_start = currdate.getTime();
	if(direction == 0)
	{
		j1w_ajaxAction('/section/next?translation_id=' + translation_id + '&first_section_id=' + first_section_id + '&first_line_no=' + first_line_no[0] + '&first_word_no=' + first_word_no,'',getSectionsResponse);
	}
	else
	{
		j1w_ajaxAction('/section/prev?translation_id=' + translation_id + '&last_section_id=' + last_section_id + '&first_line_no=' + first_line_no[0] + '&first_word_no=' + first_word_no,'',getSectionsResponse);			
	}	
}
function getNextSections(event)
{
	if(loading || ajax_loading)
	{
	    show_spinner = true;
		setTimeout("getNextSections(null)","100");
		return;
	}
	if(end_of_page == true)
	{
	    return;
	}
	loading = true;
	previous_direction = direction;
    direction = 0; //Forward
    //Move last word/line/section info to first and request data
	var skip_ajax = false;
	if(page_cache == true)
	{
	    old_first_section_id = -1;
	    page_cache=false;
	}
	else
	{
	    old_first_section_id = first_section_id;
	    old_first_line_no = first_line_no;
	    old_first_word_no = first_word_no;
		if(previous_direction == 0 && last_section_id - first_section_id < 10 && sections.length >= 10)
		{
			var section_offset = last_section_id - first_section_id;
			sections = sections.slice(section_offset);
			skip_ajax = true;
		}
	    if(last_word_no > 0)
		{
			first_section_id = last_section_id;
			first_line_no    =    last_line_no.slice();
			first_word_no    =    last_word_no;
		}
		else if (j1w_requireLine(last_line_no))
		{
			first_section_id = last_section_id;
			first_line_no    =    last_line_no.slice();
			first_word_no    =    last_word_no;
		}
		else
		{
			skip_ajax = false;
            // if(previous_direction == 0 && last_section_id - first_section_id < 10 && sections.length >= 2)
            // {
            //                 
            // //   sections = sections.slice(1);
            // //   skip_ajax = true;
            // }
			first_section_id = last_section_id+1;
			first_line_no    =    [-1];
			first_word_no    =    -1;
		}
    }
	
	if(skip_ajax)
	{
		renderPageForward();
		
	}
	else
	{
		getSections(event);
	}

}
function getPreviousSections(event)
{
    end_of_page = false;
	if(loading || ajax_loading)
	{
	    show_spinner = true;
	    
		setTimeout("getPreviousSections(null)","100")
		return;
	}
	loading = true;
    // log("Getting Previous Sections")
	previous_direction = direction;
    direction = 1; //Reverse
    if(old_first_section_id != -1)
    {
        first_section_id = old_first_section_id;
        first_line_no = old_first_line_no;
        first_word_no = old_first_word_no;
        old_first_section_id = -1;
        loading = false;
        page_cache=true;
        getNextSections();
        return;
    }
	var skip_ajax = false;
	if(previous_direction == 1 && last_section_id - first_section_id < 10 && sections.length >= 10)
	{
		var section_offset = last_section_id - first_section_id;
		sections = sections.slice(section_offset);
		skip_ajax = true;
	}	

	if(first_word_no > 0)
		{
			last_word_no = first_word_no;
			last_line_no    =    first_line_no.slice();
			last_section_id = first_section_id;
		}
	else if (j1w_requireLine(first_line_no))
	{
			last_word_no    =    first_word_no;
			last_section_id = first_section_id;
			var child_is_zero = true;
			last_line_no    =    first_line_no.slice();
	}
	else
	{
		last_word_no = first_word_no;
		last_line_no    =    first_line_no.slice();
		skip_ajax = false;
		if(previous_direction == 1 && last_section_id - first_section_id < 10 && sections.length >= 10)
		{
			sections = sections.slice(1);
			skip_ajax = true;
		}
		last_section_id = first_section_id-1;
	}
    //Move last word/line/section info to first and request data
	if(skip_ajax)
	{
		renderPageReverse();
	}
	else
	{
		getSections(event);
	}
}

function getSectionsResponse(response)
{
	sections = eval('(' + response.responseText + ')');
	if (sections.length == 0) {loading = false; return;	} // stop processing
	direction == 0 ? first_section_id = sections[0].section.section_number : last_section_id = sections[0].section.section_number;
	var currdate = new Date();
	render_benchmarks.ajax_end = currdate.getTime();
	direction == 0 ? renderPageForward() : renderPageReverse();
}

function renderPageForward()
{
	var currdate = new Date();
	
	render_benchmarks.render_forward_start = currdate.getTime();
	var current_section =     0;
	var current_line    =     first_line_no.slice();
	var current_word    =     first_word_no;
	var page_filled     =     0; //Can = 0 not filled,1 left filled, 2 left&right filled
	direction           =     0;
	content_left_html =    "";
	content_right_html =   "";
	//Render Left Side of Page
	//If first_word > 0 then run var statusCodes = wordFill;
	j1w_setInnerHTML('content_left',"");
	j1w_setInnerHTML('content_right',"");
	//If first_line > 0 and first_word_no == 0 then run var statusCodes = lineFill;
	if(j1w_requireLine(current_line) && page_filled == 0)
	{

		var statusCodes = lineFill('content_left',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		var linepref = "";
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];

		if(current_section >= sections.length)
		{
		    last_section_id = first_section_id + current_section;
        	last_line_no    = current_line;
        	last_word_no    = current_word;
			getMoreSections();
			return;
		}
		
	}

	//Try to fit as many section chunks into left page before going onto line	
	if(page_filled == 0)
	{	
		var statusCodes = sectionFill('content_left',current_section,current_line,current_word);
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];

		if(current_section >= sections.length)
		{
		    last_section_id = first_section_id + current_section;
        	last_line_no    = current_line;
        	last_word_no    = current_word;
			getMoreSections();
			return;
		}	
	}
	if(page_filled == 0)
	{
		var statusCodes = lineFill('content_left',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
		    last_section_id = first_section_id + current_section;
        	last_line_no    = current_line;
        	last_word_no    = current_word;
			getMoreSections();
			return;
		}
	}

	
	//Render Right Page of Bible
	/****************************
	-->Line,Section,Line,Word
	*****************************/
	page_filled < 2 ? page_filled = 0 : page_filled = 2;
	if( j1w_requireLine(current_line)  && page_filled == 0)
	{
		linepref = "";
		for(var h = 0;h<last_line_no.length;h++)
		{
			linepref = linepref + "," + last_line_no[h];
		}
		var statusCodes = lineFill('content_right',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
		    last_section_id = first_section_id + current_section;
        	last_line_no    = current_line;
        	last_word_no    = current_word;
			getMoreSections();
			return;
		}	
	}
		
	if( page_filled == 0)
	{
		var statusCodes = sectionFill('content_right',current_section,current_line,current_word);
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];

		if(current_section >= sections.length)
		{
		    last_section_id = first_section_id + current_section;
        	last_line_no    = current_line;
        	last_word_no    = current_word;
			getMoreSections();
			return;
		}	
	}
	if( page_filled == 0)
	{
		var statusCodes = lineFill('content_right',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
		    last_section_id = first_section_id + current_section;
        	last_line_no    = current_line;
        	last_word_no    = current_word;
			getMoreSections();
			return;
		}	
	}
	//Store new first_word and last_word_data
	//Fire Process Content to Update the bible
	last_section_id = first_section_id + current_section;
	last_line_no    = current_line;
	last_word_no    = current_word;
	var currdate = new Date();
	
	render_benchmarks.render_forward_end = currdate.getTime();
	processContent();

	if(sections.length - current_section < 7)
	{
		background_load = true;
		setTimeout('getMoreSections()',"1");
	}
	else
	{
		loading = false;
	}
}
function renderPageReverse()
{
	var current_section =     0;
	var current_line    =     last_line_no.slice();
	var current_word    =     last_word_no;
	var page_filled     =     0; //Can = 0 not filled,1 left filled, 2 left&right filled
	direction = 1;
	content_left_html =    "";
	content_right_html =   "";
	//Render Left Side of Page
	j1w_setInnerHTML('content_left',"");
	j1w_setInnerHTML('content_right',"");

	if(j1w_requireLine(current_line) && page_filled == 0)
	{
		if(previous_direction  == 0 && current_word <= 0)
		{
			var child_removed = true;
			for(var h = current_line.length - 1;h >= 0;h--)
			{
				if(child_removed)
				{
					current_line[h]--;				
					child_removed = false;
				}
				if(current_line[h] == -1)
				{
					child_removed = true;
					current_line.pop();
				}
			}
		}
		////log('*****running  last line_fill reverse');
		var statusCodes = lineFillReverse('content_right',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		previous_direction = direction;
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
			getMoreSections();
			return;
		}
	}
	//Try to fit as many section chunks into left page before going onto line	
	if(page_filled == 0)
	{
		var statusCodes = sectionFillReverse('content_right',current_section,current_line,current_word);
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
			getMoreSections();
			return;
		}
	}
	if(page_filled == 0)
	{
		var statusCodes = lineFillReverse('content_right',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
			getMoreSections();
			return;
		}	
	}
	//Render Left Page of Bible
	/****************************
	-->Line,Section,Line,Word
	*****************************/
	if( j1w_requireLine(current_line) && page_filled != -1)
	{
		var statusCodes = lineFillReverse('content_left',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
			
			getMoreSections();
			return;
		}	
	}
	if(page_filled != -1)
	{
		var statusCodes = sectionFillReverse('content_left',current_section,current_line,current_word);
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{	
			getMoreSections();
			return;
		}	
	}
	if(page_filled != -1)
	{
		var statusCodes = lineFillReverse('content_left',current_section,current_line,current_word,sections[current_section].section.content,0,[],"");
		current_section = statusCodes[0];
		current_line    = statusCodes[1];
		current_word    = statusCodes[2];
		page_filled     = statusCodes[3];
		if(current_section >= sections.length)
		{
			getMoreSections();
			return;
		}	
	 }
	if (current_section > sections.length-1)
	{
		first_section_id = 0;
		first_line_no = [-1];
		first_word_no = -1;
		direction=0;
		previous_direction = 0;
		renderPageForward();
		return;
	}
	//Store new first_word and last_word_data
	//Fire Process Content to Update the bible
	first_section_id = last_section_id - current_section;
	first_line_no    = current_line;
	first_word_no    = current_word;
	processContent();
	if(sections.length - current_section < 7)
	{
		background_load = true;
		setTimeout('getMoreSections()',"1");
	}
	else
	{
		loading = false;
	}
}

function processContent()
{
	//Code to be run to process events on BCVS
	var currdate = new Date();
	render_benchmarks.post_process_start = currdate.getTime();
	setDisplayPreferences();
	pageBcvs = $('bible_wrapper').select('span.bcv'); /*$$('span.bcv');*/
	//set the Bible header status line based on the first bcv
	if(pageBcvs.first() != null)
	{
    	var headerStatus = pageBcvs.first().readAttribute('bcv');
    	var splitHeaderStatus = headerStatus.split(".");
    	first_bcv = headerStatus;
	}
	var headerSuffix = pageBcvs.last().readAttribute('bcv');
	last_bcv = headerSuffix;
	var splitHeaderSuffix = headerSuffix.split(".");
    var titleSearchField = j1w_getElementById('title_search_textfield')
	if (titleSearchField != null && pageBcvs.first() != null) {
	    var tsFieldState = titleSearchField.getAttribute('readstate');
	    if(tsFieldState != 'locked'){
	        var previousLink = j1w_getElementById('title_previous_item');
	        var nextLink = j1w_getElementById('title_next_item');
    		(splitHeaderStatus[2] != "0" && splitHeaderStatus[2] != "00" )  ? startverse = splitHeaderStatus[2] : startverse = "1";
    		if(splitHeaderStatus[1] == "0"){ splitHeaderStatus[1] = "1" };
    		titleSearchField.value = books[parseInt(splitHeaderStatus[0])-1] + " " + splitHeaderStatus[1] + ":" + startverse;		
	        previousLink.setAttribute("href", "/bible?bcv=" + books[parseInt(splitHeaderStatus[0])-1].replace(/\s/, '-') + "_" + (parseInt(splitHeaderStatus[1]) - 1))
	        nextLink.setAttribute("href", "/bible?bcv=" + books[parseInt(splitHeaderStatus[0])-1].replace(/\s/, '-') + "_" + (parseInt(splitHeaderStatus[1]) + 1))
	    } else {
	        titleSearchField.removeAttribute('readstate');
	    }
	}
    // if (j1w_getElementById('bible_right_page_header') != null)
    // {
    //  splitHeaderSuffix[2] != "0" ? startverse = splitHeaderSuffix[2] : startverse = "1";
    //  if(splitHeaderSuffix[1] == "0"){ splitHeaderSuffix[1] = "1" };
    //  j1w_setInnerHTML('bible_right_page_header',"<b>" + books[splitHeaderSuffix[0]-1] + "</b>&nbsp;&nbsp;" + splitHeaderSuffix[1] + ":" + startverse);       
    // }
	if(splitHeaderStatus != null) {
	    splitHeaderStatus[2] != "0" ? startverse = parseInt(splitHeaderStatus[2]) : startverse = 1;
	    if(splitHeaderSuffix != null) {
	        splitHeaderSuffix[2] != "0" ? endverse = parseInt(splitHeaderSuffix[2]) : endverse = 1;	  
            updateSbmenuWithoutRequest('', parseInt(splitHeaderStatus[0]), parseInt(splitHeaderStatus[1]), startverse);             
        }
	}
	else {
	    // UPDATE THE BCV QUICK SELECT (GEN 1:1 DEFAULTING HERE)
        updateSbmenuWithoutRequest('genesis_1:1', 1, 1, 1);
	}
    addEventsToBcvs();
    Comment.loadForRange(first_bcv, last_bcv, 1);
	$('showFootnote').innerHTML = "";
	strayChapterTags = $('bible_wrapper').select('span.c');
	strayChapterTags.each(function(strayChapter){
		if(strayChapter.innerHTML == null || strayChapter.innerHTML == "") {
			strayChapter.remove();
		}
	});
	straySubTitleTags = $('bible_wrapper').select('span.s');
	straySubTitleTags.each(function(straySubTitle){
		if(straySubTitle.innerHTML == null || straySubTitle.innerHTML == "") {
			straySubTitle.remove();
		}
	});
	//This code calls functions to get user_bible_data
	setTimeout("getUserBibleData('" + first_bcv + "','" + last_bcv + "' )","1000");
	var currdate = new Date();
	render_benchmarks.post_process_end = currdate.getTime();
}
function logBenchmarks()
{
	var ajax_load_time = render_benchmarks.ajax_end - render_benchmarks.ajax_start;
	var render_load_time = render_benchmarks.render_forward_end - render_benchmarks.render_forward_start;
	var post_process_time = render_benchmarks.post_process_end - render_benchmarks.post_process_start;
	log("Ajax Response Time: " + ajax_load_time + "(ms)" )
	log("Page Forward Render Time: " + render_load_time + "(ms)" )
	log("Post Process Time: " + post_process_time + "(ms)" )
	log("Total Render Time: " + (render_load_time + post_process_time) + "(ms)" );
	if(beta_mode)
	{
		j1w_ajaxAction('/section/log_chopper_data','ajax_time=' + ajax_load_time + "&render_forward=" + render_load_time + "&render_post=" + post_process_time,null);
	}
}

/*******************************************************
   Function: sectionFill
   Description : Fills a column of the bible with sections until overflow is detected
   input parameters: 
	id              --       Div id of current element being populated
	current_section --    current section data index in array sections
	current_line    --  current line being rendered in current section
	current_word    --	current word being rendered in current section
   output parementers:
		[current_section,current_line,current_word,filled]
		filled -- 1 = left page filled, 2 = right page
		
  Revision History:
  
  04/21/2009 -- David Estes -- Function Created

/*******************************************************/
function sectionFill(id,current_section,current_line,current_word)
{
	var filled         =                                0;
	var currentElement =           j1w_getElementById(id);
	var currentElementWrapper = j1w_getElementById(id + "_wrapper");
	var left           =  j1w_getElementById('left_page');
	var right          = j1w_getElementById('right_page');
	var currentSectionBuffer = j1w_createElement('div');
	for(;current_section < sections.length; current_section++)
	{
		j1w_setInnerHTML(currentSectionBuffer,sections[current_section].section.content);
		
		if(current_section > 0 && j1w_containsElements(currentSectionBuffer,["mbk"]))
		{
			filled = 2;
			current_section--;
			break;
		} 
		id == "content_left" ? j1w_setInnerHTML(id,content_left_html + sections[current_section].section.content) : j1w_setInnerHTML(id,content_right_html + sections[current_section].section.content);
			if(j1w_getScrollHeight(currentElementWrapper) > ((id == 'content_right') ? j1w_getClientHeight(right) : j1w_getClientHeight(left)))
			{
				break;
			}
			else
			{
				id == "content_left" ? content_left_html = content_left_html + sections[current_section].section.content : content_right_html = content_right_html + sections[current_section].section.content;
			}
	}
	current_line = [-1];
	id == "content_left" ? j1w_setInnerHTML(id,content_left_html) : j1w_setInnerHTML(id,content_right_html)
	current_word = -1;
	return [current_section,current_line,current_word,filled];
}
/*******************************************************
   Function: sectionFillReverse
   Description : Fills a column of the bible view
                 with sections until overflow is detected in reverse
   input parameters: 
	id              --       Div id of current element being populated
	current_section --    current section data index in array sections
	current_line    --  current line being rendered in current section
	current_word    --	current word being rendered in current section
   output parementers:
		[current_section,current_line,current_word,filled]
		filled -- 1 = left page filled, 2 = right page
		
  Revision History:
  
  04/21/2009 -- David Estes -- Function Created

/*******************************************************/
function sectionFillReverse(id,current_section,current_line,current_word)
{
	var filled         =                                0;
	var currentElement =           j1w_getElementById(id);
	var currentElementWrapper = j1w_getElementById(id + "_wrapper");
	var left           =  j1w_getElementById('left_page');
	var right          = j1w_getElementById('right_page');
	
	for(;current_section < sections.length; current_section++)
	{
		//Add Check for classnames of mbk

		id == "content_left" ? j1w_setInnerHTML(id,sections[current_section].section.content + content_left_html) : j1w_setInnerHTML(id,sections[current_section].section.content + content_right_html);
			
			if(j1w_getScrollHeight(currentElementWrapper) > ((id == 'content_right') ? j1w_getClientHeight(right) : j1w_getClientHeight(left)))
			{
				//id == "content_right" ? filled = 2 : filled = 1
				break;
			}
			else
			{
				id == "content_left" ? content_left_html = sections[current_section].section.content + content_left_html : content_right_html = sections[current_section].section.content + content_right_html;
			}
		//In reverse we use slightly diferent logic for mt and mt1 tags, but that isn't
		//done until we encounter wordFillReverse
		if(current_section >= 0 && j1w_containsElements(currentElement,["mbk"]))
		{
			filled = -1;
            // current_section--;
            // console.log('testing this in reverse');
			var temp_buffer = pageFill(id,"");
			id == "content_left" ? content_left_html =temp_buffer + content_left_html : content_right_html = temp_buffer + content_right_html; 
			break;
		}
	}
	current_line = [-1];
	current_word = -1;
	id == "content_left" ? j1w_setInnerHTML(id,content_left_html) : j1w_setInnerHTML(id,content_right_html)
	
	return [current_section,current_line,current_word,filled]
}


function pageFill(id,buffer)
{
	var currentElement       =                                            j1w_getElementById(id);
	var currentElementWrapper =                             j1w_getElementById(id + "_wrapper");
	var left                 =                                   j1w_getElementById('left_page');
	var right                =                                  j1w_getElementById('right_page');
	while(true)
	{
		id == "content_left" ? j1w_setInnerHTML(id,"<br/>" + buffer + content_left_html) : j1w_setInnerHTML(id,"<br/>" + buffer + content_right_html);
		if(j1w_getScrollHeight(currentElementWrapper) > ((id == 'content_right') ? j1w_getClientHeight(right) : j1w_getClientHeight(left)))
		{
			break;
		}
		else
		{
			buffer = "<br/>" + buffer;
		}
	}
	return buffer;
}

/*******************************************************
   Function: lineFill
   Description : Fills a column of the bible with lines until overflow is detected
   input parameters: 
	id              --       Div id of current element being populated
	current_section --    current section data index in array sections
	current_line    --  current line being rendered in current section
	current_word    --	current word being rendered in current section
   output parementers:
		[current_section,current_line,current_word,filled]
		filled -- 1 = left page filled, 2 = right page
		
  Revision History:
  
  04/21/2009 -- David Estes -- Function Created

/*******************************************************/
function lineFill(id,current_section,current_line,current_word,data,current_level,close_tags,parent_buffer)
{
	
	var filled               =                                                                 0;
	var currentElement       =                                            j1w_getElementById(id);
	var currentElementWrapper =                             j1w_getElementById(id + "_wrapper");
	var left                 =                                   j1w_getElementById('left_page');
	var right                =                                  j1w_getElementById('right_page');	
	var lines                =    								j1w_getChildNodesFromString(data);
	var instance_buffer      =                                  parent_buffer;
	var prefix = "";
	var funclineFill = lineFill;
	var funcj1w_setInnerHTML = j1w_setInnerHTML
	
	if(current_level == 0)
	{
		filled = 0;
	}
	if(lines.length == 0)
	{
		current_line.pop();
		return [current_section,current_line,current_word,filled,instance_buffer];
	}
	if(current_line[current_level] == -1)
	{
		current_line[current_level] = 0;
	}
	for(;current_line[current_level] < lines.length ; current_line[current_level]++)
	{
		//Make sure we are drilled down to the cuurrent most level, if not iterate
		var linepref = "";

		if(current_level == current_line.length -1)
		{
			//If we are drilled down to current level do stuff, otherwise we need to keep drilling down
			if(current_word > 0) //See if this level requires a wordFill
			{
				//Fill Words
				 instance_buffer = instance_buffer + lines[current_line[current_level]][0];
				instance_buffer = instance_buffer.replace("<span class=\"p0\">","<span class=\"m0\">");
				instance_buffer = instance_buffer.replace("<span class=\"p1\">","<span class=\"m1\">");
				close_tags.push(lines[current_line[current_level]][1]);
				status = wordFill(id,current_word,lines[current_line[current_level]][2],close_tags,instance_buffer);	
				current_word       = status[0];
				instance_buffer    = status[1];	
				close_tags.pop();
			}
			else //If not we need to fill in this line and test for overflow
			{
				var tagstring = dumpTags(close_tags);
			    if(lines[current_line[current_level]][0] == "<span class\"col\">" || lines[current_line[current_level]][0].startsWith("<span class=\"c\""))
				{
					id == "content_left" ? funcj1w_setInnerHTML(id,content_left_html + instance_buffer + lines[current_line[current_level]][0]+ lines[current_line[current_level]][2] + lines[current_line[current_level]][1] + "<br style\"clear:both\"/>" + tagstring) : funcj1w_setInnerHTML(id,content_right_html +  instance_buffer + lines[current_line[current_level]][0]+ lines[current_line[current_level]][2] + lines[current_line[current_level]][1] + "<br style\"clear:both\"/>" + tagstring) ;
				}
				else
				{
					id == "content_left" ? funcj1w_setInnerHTML(id,content_left_html + instance_buffer + lines[current_line[current_level]][0]+ lines[current_line[current_level]][2] + lines[current_line[current_level]][1] + tagstring) : funcj1w_setInnerHTML(id,content_right_html +  instance_buffer + lines[current_line[current_level]][0]+ lines[current_line[current_level]][2] + lines[current_line[current_level]][1] + tagstring) ;
				}
				if(current_section > 0 && lines[current_line[current_level]][2].match('class="mbk"') != null)
				{
					filled = 2;
					break;
				}
				//Now check if it overflowed the page, if it did we need to drill down into that line and keep going
				if(j1w_getScrollHeight(currentElementWrapper) > ((id == 'content_right') ? j1w_getClientHeight(right) : j1w_getClientHeight(left)))
				{
					instance_buffer = instance_buffer + lines[current_line[current_level]][0];
					close_tags.push(lines[current_line[current_level]][1]);
					if(current_level == current_line.length -1)
					{
						current_line.push(0);
					}
					var status = funclineFill(id,current_section,current_line,current_word,lines[current_line[current_level]][2],current_level + 1,close_tags,instance_buffer);
					current_section = status[0];
					current_line    = status[1];
					current_word    = status[2];
		 			filled          = status[3];
					instance_buffer = status[4];
					if(current_level == current_line.length -1 && current_word <= 0 && lines[current_line[current_level]][0].startsWith("<span class=\"c\"") == false)
					
					{
					 	status = wordFill(id,current_word,lines[current_line[current_level]][2],close_tags,instance_buffer);	
						current_word       = status[0];
						instance_buffer    = status[1];
					}
					close_tags.pop();
					if(instance_buffer.endsWith(lines[current_line[current_level]][0]))
					{
						instance_buffer = instance_buffer.substr(0,instance_buffer.length-lines[current_line[current_level]][0].length);
					}
					filled =1;
					break;
				}
				else
				{
					instance_buffer = instance_buffer + lines[current_line[current_level]][0]+ lines[current_line[current_level]][2] + lines[current_line[current_level]][1];
				}
			}
		}
		else
		{
			instance_buffer = instance_buffer + lines[current_line[current_level]][0];
			close_tags.push(lines[current_line[current_level]][1]);
			var status = funclineFill(id,current_section,current_line,current_word,lines[current_line[current_level]][2],current_level + 1,close_tags,instance_buffer);
			current_section = status[0];
			current_line    = status[1];
			current_word    = status[2];
 			filled          = status[3];
			instance_buffer = status[4];
			if(instance_buffer.endsWith(lines[current_line[current_level]][0]))
			{
				instance_buffer = instance_buffer.substr(0,instance_buffer.length-lines[current_line[current_level]][0].length);
			}
			close_tags.pop();
			if(filled == 1)
			{
				break;
			}
		}
	}
	var tagstring = dumpTags(close_tags);
	if(close_tags.length >= 1 && current_level <= current_line.length -1)
	{
		instance_buffer = instance_buffer + close_tags[close_tags.length-1];
	}
	if(current_level == 0)
	{
		id == "content_left" ? content_left_html = content_left_html + instance_buffer : content_right_html = content_right_html + instance_buffer;
		id == "content_left" ? j1w_setInnerHTML(id,content_left_html) : j1w_setInnerHTML(id,content_right_html);
		if(current_line[0] == lines.length)
		{
			current_section = current_section + 1;
			current_line[0] = -1;
		}
		var linepref = "";
		for(x = 0 ; x<current_line.length;x++)
		{
			linepref = linepref + current_line[x] + ",";
		}
	}else
	{
		if(current_line[current_level] == lines.length)
		{
			current_line.pop();
		}
	}
	return [current_section,current_line,current_word,filled,instance_buffer];
}
function lineFillReverse(id,current_section,current_line,current_word,data,current_level,open_tags,parent_buffer)
{
	var filled               =                                                                 0;
	var currentElement       =                                            j1w_getElementById(id);
	var currentElementWrapper =                             j1w_getElementById(id + "_wrapper");
	var left                 =                                   j1w_getElementById('left_page');
	var right                =                                  j1w_getElementById('right_page');	
	var lines                =                                 j1w_getChildNodesFromString(data);
	var instance_buffer      =                                                     parent_buffer;
	var prefix = "";

	if(current_line[current_level] == -1)
	{
		current_line[current_level] = lines.length-1;
	}
	var linepref = "";
	for(var g = 0;g<current_line.length;g++)
	{
		linepref = linepref + "," + current_line[g];
	}
	if(lines.length == 0)
	{
		current_line.pop();
		return [current_section,current_line,current_word,filled,instance_buffer];
	}
	for(g = 0;g<current_level;g++)
	{
		prefix = prefix + "-";
	}
		for(;current_line[current_level] >= 0 ; current_line[current_level]--)
		{
			//Make sure we are drilled down to the cuurrent most level, if not iterate
			if(current_level == current_line.length -1)
			{
				//If we are drilled down to current level do stuff, otherwise we need to keep drilling down
				if(current_word > 0) //See if this level requires a wordFill
				{
					//Fill Words
				    instance_buffer = lines[current_line[current_level]][1] + instance_buffer;
					open_tags.push(lines[current_line[current_level]][0]);
					status = wordFillReverse(id,current_word,lines[current_line[current_level]][2],open_tags,instance_buffer);	
					current_word       = status[0];
					instance_buffer    = status[1];	
					open_tags.pop();
				}
				else //If not we need to fill in this line and test for overflow
				{
					var tagstring = dumpTags(open_tags);
					id == "content_left" ? j1w_setInnerHTML(id,tagstring + lines[current_line[current_level]][0] + lines[current_line[current_level]][2] + lines[current_line[current_level]][1] + instance_buffer + content_left_html) : j1w_setInnerHTML(id,tagstring + lines[current_line[current_level]][0] + lines[current_line[current_level]][2] + lines[current_line[current_level]][1] + instance_buffer + content_right_html) ;
					//Now check if it overflowed the page, if it did we need to drill down into that line and keep going
					if(j1w_getScrollHeight(currentElementWrapper) > ((id == 'content_right') ? j1w_getClientHeight(right) : j1w_getClientHeight(left)))
					{
						if(lines[current_line[current_level]][0].match("class=\"mbk\""))
						{
                            current_section--;
                            current_word=-1;
                            current_line = [-1];
                            filled=-1;
							break;
						}
						instance_buffer = lines[current_line[current_level]][1] + instance_buffer;
						open_tags.push(lines[current_line[current_level]][0]);
						if(current_level == current_line.length -1)
						{
							current_line.push(-1);
						}
						var status = lineFillReverse(id,current_section,current_line,current_word,lines[current_line[current_level]][2],current_level + 1,open_tags,instance_buffer);
						current_section = status[0];
						current_line    = status[1];
						current_word    = status[2];
			 			filled          = status[3];
						instance_buffer = status[4];
						if(current_level == current_line.length -1 && current_word <= 0)
						{
							if(open_tags.length > 0)
							{
								for(var g = open_tags.length -1;g >= 0 ; g--)
								{
							 		if(open_tags[g] == "<span class=\"p0\">" )
									{
										open_tags[g] = "<span class=\"m0\">";
									}
									if(open_tags[g] == "<span class=\"p1\">" )
									{
										open_tags[g] = "<span class=\"m1\">";
									}
								}
							}
						 	status = wordFillReverse(id,current_word,lines[current_line[current_level]][2],open_tags,instance_buffer);	
							current_word       = status[0];
							instance_buffer    = status[1];
						}
						open_tags.pop();

						if(instance_buffer.startsWith(lines[current_line[current_level]][1]))
						{
							instance_buffer = instance_buffer.substr(lines[current_line[current_level]][1].length);

						}
						filled = 1;
						break;
					}
					else
					{
						instance_buffer = lines[current_line[current_level]][0]+ lines[current_line[current_level]][2] + lines[current_line[current_level]][1]  + instance_buffer;
					}
				}
			}
			else
			{
				instance_buffer = lines[current_line[current_level]][1] + instance_buffer ;
				open_tags.push(lines[current_line[current_level]][0]);
				var status = lineFillReverse(id,current_section,current_line,current_word,lines[current_line[current_level]][2],current_level + 1,open_tags,instance_buffer);
				current_section = status[0];
				current_line    = status[1];
				var linepref = "";
				for(var g = 0;g<current_line.length;g++)
				{
					linepref = linepref + "," + current_line[g];
				}
				current_word    = status[2];
	 			filled          = status[3];
				instance_buffer = status[4];
				if(instance_buffer.startsWith(lines[current_line[current_level]][1]))
				{
					instance_buffer = instance_buffer.substr(lines[current_line[current_level]][1].length);
				}
				open_tags.pop();
				if(filled == 1)
				{
					break;
				}
			}
			//Check to see if beginning of book is in this line, if so break out to format accordingly
			if(instance_buffer.match("class=\"mbk\"") != null)
			{
				filled = -1;
				instance_buffer = pageFill(id,instance_buffer);
				current_line[current_level]--;
                current_section--;
                current_word=-1;
                current_line = [-1];
				break;
			}
		}
		var tagstring = dumpTags(open_tags);
		if(open_tags.length >= 1 && current_level <= current_line.length -1)
		{
			instance_buffer = open_tags[open_tags.length-1] + instance_buffer;
		}
		if(current_level == 0)
		{
			id == "content_left" ? content_left_html =  instance_buffer + content_left_html : content_right_html = instance_buffer + content_right_html;
			id == "content_left" ? j1w_setInnerHTML(id,content_left_html) : j1w_setInnerHTML(id,content_right_html);
			if(current_line[0] == -1)
			{
				current_section = current_section + 1;
				current_line[0] = 0;
			}
			var linepref = "";
		}else
		{
			if(current_line[current_level] == -1)
			{
				current_line.pop();
			}
		}
		return [current_section,current_line,current_word,filled,instance_buffer];
}
function wordFill(id,current_word,data,close_tags,parent_buffer)
{
	var word_buffer          =                                "";
	var new_current_word     =                                 0;
	var currentElement       =            j1w_getElementById(id);
	var currentElementWrapper =                             j1w_getElementById(id + "_wrapper");
	var left                 =   j1w_getElementById('left_page');
	var right                =  j1w_getElementById('right_page');
	var instance_buffer 	 =                     [parent_buffer];
	var word_inst_buffer     =                                "";
	var notdone = false;
	for(var counter = 0;counter < data.length ; counter++)
	{
		word_buffer = word_buffer + data.charAt(counter);
		if(data.charAt(counter) == ' ' || counter == data.length -1)
		{		
			if(current_word <= new_current_word && word_buffer != "")
			{
				var tagstring = dumpTags(close_tags);
				id == "content_left" ? j1w_setInnerHTML(id,content_left_html + instance_buffer.join('') + word_buffer + tagstring) : j1w_setInnerHTML(id,content_right_html +  instance_buffer.join('') + word_buffer +tagstring) ;
				if(j1w_getScrollHeight(currentElementWrapper) > ((id == 'content_right') ? j1w_getClientHeight(right) : j1w_getClientHeight(left)))
				{
					notdone = true;
					break;
				}
				else
				{
				 	instance_buffer.push(word_buffer);
				}
			}
			if(word_buffer != "")
			{
				new_current_word++;
			}
			word_buffer = "";
		}
	}
	if(counter >= data.length - 1 && notdone == false)
	{
		new_current_word = 0;
	}
	if(close_tags.length >= 1)
	{
		instance_buffer.push(close_tags[close_tags.length-1]);
	}
	return [new_current_word,instance_buffer.join('')];
}


function wordFillReverse(id,current_word,data,open_tags,parent_buffer)
{
	var word_buffer          =                                "";
	var new_current_word     =                                 0;
	var currentElement       =            j1w_getElementById(id);
	var currentElementWrapper =                             j1w_getElementById(id + "_wrapper");
	var left                 =   j1w_getElementById('left_page');
	var right                =  j1w_getElementById('right_page');
	var instance_buffer 	 =                     parent_buffer;
	var word_inst_buffer     =                                "";
	var counter = 0;
	for(;counter < data.length; counter++)
	{
		word_buffer = word_buffer + data.charAt(counter);
		if(data.charAt(counter) == ' ' || counter == data.length-1)
		{
			if(word_buffer != "")
			{
				new_current_word++;
			}
			if(current_word == new_current_word)
			{
				break;
			}
			word_buffer = "";
		} 
	}
	word_buffer = "";
	if(data.charAt(counter) == " " && counter > 0)
	{
		counter--;
	}
	for(;counter >= 0 ; counter--)
	{
		word_buffer = data.charAt(counter) + word_buffer;
		var notdone = false;
		if(data.charAt(counter) == ' ' || counter == 0)
		{	
			if(word_buffer != "")
			{
				var tagstring = dumpTags(open_tags);
				id == "content_left" ? j1w_setInnerHTML(id,tagstring + word_buffer + instance_buffer + content_left_html) : j1w_setInnerHTML(id,tagstring + word_buffer + instance_buffer + content_right_html) ;
				if(j1w_getScrollHeight(currentElementWrapper) > ((id == 'content_right') ? j1w_getClientHeight(right) : j1w_getClientHeight(left)))
                {
					notdone = true;
					break;
				}
				else
				{
				 	instance_buffer = word_buffer + instance_buffer;
				}
			}
			if(word_buffer != "")
			{
				new_current_word--;
			}
			word_buffer = "";
		}
	}
	if(counter == -1 && notdone == false)
	{
		new_current_word = -1;
	}
	if(open_tags.length >= 1)
	{
		instance_buffer = open_tags[open_tags.length-1] + instance_buffer;
	}
	return [new_current_word,instance_buffer];
}
function dumpTags(tags)
{
	var tempstring = ""
	for (x = 0 ; x< tags.length;x++)
	{
		tempstring = tempstring + tags[x];
	}
	return tempstring;
}
function log(t) {
	if (Prototype.Browser.Gecko || Prototype.Browser.WebKit)
		if (window.console)
			console.log(t);
}
function bible_paginated_item(direction){
    pagination_select = $('bible_topic_pagination')
    current_selected_index = pagination_select.selectedIndex
    if((current_selected_index > 0  && direction == -1)|| (current_selected_index < pagination_select.length - 1 && direction == 1)){
		pagination_select[current_selected_index + direction].selected = true;
        goToVerse(pagination_select[current_selected_index + direction].value)
    }
}
function findDesiredBcv(bcv) {
    pageBcvs = $('bible_content').select('span.bcv'); /*$$('span.bcv');*/
    var found_it = false;
    pageBcvs.each(function(e) {
        var bcv_attr = e.readAttribute('bcv');
        if(bcv_attr == bcv) {
            found_it = true;
        }
    });
    if(!found_it) {
        getNextSections(null);
    }
}