function adjustSize(pixels) {
	
	height = $(window).height();
	height-= 168 + 20;
	
	$('div.section1-content, div.section2-content').css({height: height});
	$('div#read-results1, div#read-results2, ').css({height: (height - 20)});
	$('div#search-results1, div#search-results2').css({height: (height - 90)});
	
}

/* =================================== Bible Class =================================== */

function Bible(options) {
	
	/* =================================== Properties =================================== */
	
	this.self = this;
	
	this.settings = {
	
		// the properties that must be jQuery Selectors must be unique identifiers, no classes
		parentContainer:	'#primary',
		inputField:			'#bible-fields', // jQuery Selector
		readResults:		'#read-results', //jQuery Selector
		searchResults:		'#search-results', //jQuery Selector
		
		preloadWithPassage:	'John 1',
		
		searchType:			'exactPhraseSearch',
		searchResultsPerPage: 10000,
		timeout:			10000,
		readTheme:			'verse', // verse
		searchTheme:		'default',
		delay:				1000
		
	}	
	
	this.url				= '/engine/bible-handler.php';
	this.xhr				= null;
	this.startBibleId		= null;
	this.endBibleId			= null;
	this.middle				= null;
	
	this.readCount			= 0;
	this.searchCount		= 0;
		
	this.currentReference	= null;
	this.topVerse			= null;
	this.currentSearchQuery = null;
	this.loading			= false;
	this.loadingIndicator	= '/images/icons/loading.gif';
	
	this.loadmore			= 200;
	
	this.searchPage			= 0;
	this.preserveSearchResults = 0; // 1 or 0

	this.books 		= ['Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua', 'Judges', 'Ruth', '1 Samuel', '2 Samuel', '1 Kings', '2 Kings', '1 Chronicles', '2 Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job', 'Psalm', 'Psalms', 'Proverbs', 'Ecclesiastes', 'Song Of Solomon', 'Isaiah', 'Jeremiah', 'Lamentations', 'Ezekiel', 'Daniel', 'Hosea', 'Joel', 'Amos', 'Obadiah', 'Jonah', 'Micah', 'Nahum', 'Habakkuk', 'Zephaniah', 'Haggai', 'Zechariah', 'Malachi', 'Matthew', 'Mark', 'Luke', 'John', 'Acts', 'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians', 'Philippians', 'Colossians', '1 Thessalonians', '2 Thessalonians', '1 Timothy', '2 Timothy', 'Titus', 'Philemon', 'Hebrews', 'James', '1 Peter', '2 Peter', '1 John', '2 John', '3 John', 'Jude', 'Revelation'];
	
	this.keycodes 	= {
		
		ENTER: 		13,
		BACKSPACE: 	8,
		TAB:		9,
		ESCAPE:		27,
		LEFTARROW:	37,
		RIGHTARROW: 39,
		DOWNARROW:	40,
		UPARROW:	38,
		COMMA:		188
		
	};
	
	// merge passed options with default settings
	
	if(options) {
					
		this.settings = $.extend( this.settings, options );
	
	}
	
	this.init();

}

/* =================================== Bible Class Methods =================================== */

Bible.prototype.init = function() {
		
	var instance = this.self;
	
	this.get(this.settings.preloadWithPassage);
	
	$(instance.settings.inputField).keyup(function(e) {					
		
		instance.keyUp(e, this);
				
	})
	
	$(this.settings.parentContainer+' img.back-button').click(function() {
	
		var type = $(this).attr('type');
		instance.showWhichResults(type)
				
	});
	
	$(this.settings.parentContainer+' ul.advanced-search-options li').live('click', function() {
	
		instance.settings.searchType = $(this).attr('type');
		instance.applySelectedSearchType();
		
		instance.currentSearchQuery = $(instance.settings.parentContainer+' span.search-query').html().replace(/"/g, '');
		
		//console.log(instance.currentSearchQuery);
		
		instance.preserveSearchResults = 0;
		instance.get(instance.currentSearchQuery);
		
	});
	
	$(this.settings.parentContainer+' img.analytics-icon, '+this.settings.parentContainer+' img.close-analytics').live('click', function() {
		
		analytics = $(instance.settings.parentContainer+' div.analytics');
		
		if( $(analytics).css('display') == 'none' ) {
			
			$(analytics).css({display: 'block'});
			
		}
		
		else {
			
			$(analytics).css({display: 'none'});
		
		}
		
	});
	
}

Bible.prototype.applySelectedSearchType = function() {
	
	$(this.settings.parentContainer+' ul.advanced-search-options li').removeClass('selected-search-type');
	$(this.settings.parentContainer+' ul.advanced-search-options li[type='+this.settings.searchType+']').addClass('selected-search-type');
	
}

Bible.prototype.abort = function() {
				
	if(this.xhr != null) 
		this.xhr.abort();
}

Bible.prototype.setStartAndLastVerse = function() {
	
	size = $(this.settings.readResults+' p').size();
			
	this.startId 	= $(this.settings.readResults+' p:eq(0) span[bible_id]').attr('bible_id');
	this.endId 		= $(this.settings.readResults+' p:eq('+(size - 1)+') span[bible_id]').attr('bible_id');
			
}

Bible.prototype.unbindScrollStop = function() {

	$(this.settings.readResults).unbind('scrollstop');
	
}

Bible.prototype.scrollStop = function() {

	var instance = this.self;
			
	$(this.settings.readResults).bind('scrollstop', function(e){
			
		minimum = 100000;
		reference = null;				
		scrollPosition = $(this).scrollTop();
		
		scrollPosition = scrollPosition;
		
		$(instance.settings.readResults+' p').each(function(i) {
			
			topPosition = Math.abs($(this).position().top);
																	
			if(topPosition < minimum) {
				minimum = topPosition;
				reference = $(this).children('span[reference]').attr('reference');
			}

		});
		
		instance.topVerse = reference;									
		$(instance.settings.inputField).val(reference);		
		
		//console.log(instance.topVerse);
		//console.log(instance.currentSearchQuery);

			
	});

}

Bible.prototype.goto = function(reference, animate) {

	var instance = this.self;

	this.loading = true;
	
	//console.log(instance.settings.readResults);
	
	//handle Song of Solomon

	pattern = 'Song Of Solomon'; 
	reference = reference.replace(pattern, 'Song of Solomon');
		
	match = $(instance.settings.readResults+' span[reference="'+reference+'"]');
	
	//console.log(match);
	
	coords = $(match).position().top;

	current = $(this.settings.readResults).scrollTop();
	
	
	
	if(animate != true) {
		
		$(this.settings.readResults).scrollTop( (current + coords));	
		this.loading = false;
		$(instance.settings.readResults).bind('scroll', function() {
		
			instance.loadOnScroll();
		
		});	

		
	}
	
	else {
		
		//this.unbindScrollStop();
	
		/*console.log(reference);
		console.log('coords for match: '+coords);
		console.log('current Scroll Position: '+current);
		*/
		
		//console.log($(instance.settings.readResults+' span:last'));
		
		middle = $(instance.settings.readResults+' span:last').position().top / 2;
		
		//console.log(middle);
		
		$(this.settings.readResults).scrollTop(middle);
		
		
		
		//console.log($(this.settings.readResults).outerHeight());

		$(this.settings.readResults).animate({
			//animate to what? 
			scrollTop: (current + coords)
		}, 
					
		150, //duration of the entire animation
				
		function() { // a callback function once the animation is completed		
		
			instance.loading = false;
			
			$(instance.settings.readResults).bind('scroll', function() {
		
				instance.loadOnScroll();
		
			});	
		
		});
	
	}
	
	this.scrollStop();
		
}

Bible.prototype.loadOnScroll = function() {
				
	curScroll = $(this.settings.readResults)[0].scrollTop;
	maxScroll = $(this.settings.readResults)[0].scrollHeight - $(this.settings.readResults).height() - 20;
					
	// at top of div
	
	if(curScroll <= this.loadmore) {
		
		//console.log(curScroll);
		
			if(this.startId != 1 ) {
			
			if(this.loading == true) {
				return false;
				
			} 
							
			//console.log('called');
			this.get('', '', 'load', 'up');
		
		}
		
		//console.log('top');
		
	}
	
	//at bottom of div
				
	if(curScroll >= (maxScroll - this.loadmore)) {
		
		if(this.endId != 31102) {
		
			if(this.loading == true) {
				return false;
				
			}
		
			this.get('', '', 'load', 'down');
		
		}
		
		//console.log('bottom');
	
	}

}

Bible.prototype.jumpToVerse = function(reference) {
	
	this.preserveSearchResults = 1;
	
	var instance = this.self;
		
	$(this.settings.inputField).val(reference);
	this.get(reference);

	//add back to search button
	
	pos = $(this.settings.inputField).position();
	w = $(this.settings.inputField).width();

}

Bible.prototype.keyUp = function(e, field) {

	q = $(field).val();

		
	if(q.length == 0) {
		
		return;
		
	}

	if(e.which == this.keycodes.ESCAPE) {
	
		$(field).val('');
		return;
	}
	
	if(e.which == this.keycodes.LEFTARROW || e.which == this.keycodes.RIGHTARROW) {
		return;
	}
	
	if(e.which == this.keycodes.DOWNARROW || e.which == this.keycodes.UPARROW) {
		
		//methods.navigateList(e.which);
		return;
		
	}

	if(e.which == this.keycodes.ENTER) {
	
		this.preserveSearchResults = 0;
		$('img.back-to-search-button').remove();
		this.get(q);
		
	}

}

Bible.prototype.get = function(q, limit, type, direction) {
	
	var instance = this.self;
			
	if(this.loading == true) {
		return;
	}
	
	//return;
	//unbind loadOnScroll
	
	this.loading = true;
	this.unbindScrollStop();
	$(this.settings.readResults).unbind('scroll');
		
	// determine data string to be sent to server

	if(type == 'load') {

		dataString = 'type=load&direction='+direction+'&start='+this.startId+'&end='+this.endId;

	}
	
	else {
		
		this.currentSearchQuery = q;
		
		dataString = 'q='+escape(q)+'&type=q&searchType='+this.settings.searchType+'&limit='+this.settings.searchResultsPerPage+'&preserveSearchResults='+this.preserveSearchResults;
	
	}

	//abort any outstanding ajax request
	
	this.abort();

	this.xhr = $.ajax({
	
		url: this.url,
		data: dataString,
		dataType: 'json',
		async: true,
		cache: true,
		timeout: this.timeout,
		type: 'post',
		
		beforeSend: function() {
			
			//add loading indicator 
			var str = '<img class="loading-indicator" src="'+instance.loadingIndicator+'" alt="Loading" />';
			$(instance.settings.parentContainer+' div.input-area').append(str);
			
			instance.backButtonHandler();
			
		},
		
		success: function(data) {
			
			//remove loading indicator 
			$(instance.settings.parentContainer+' div.input-area img.loading-indicator').remove();
			
			//handle search analytics box 
			
			//console.log(instance.preserveSearchResults);
			
			if(instance.preserveSearchResults == 1) {
				$(instance.settings.parentContainer+' div.analytics').css({display: 'none'});
			}
			
			else {
				$(instance.settings.parentContainer+' div.analytics').remove();
			}
			
			
			
			instance.xhr = null;				
						
			readResults = false;
			searchResults  = false;			
							
			// If there is scripture to read				
										
			if(data.read != 'empty' && data.read != false) {
			
				readResults = true;
			
				instance.currentReference 		= data.reference.book+' '+data.reference.chapter+':'+data.reference.verse;
				instance.middle					= data.middle;				
				instance.readCount = data.read.scripture.length;
			}
			
			else {
				
				instance.readCount = 0;
				
			}
			
					
				
			// If there are search results to display
																	
			if(data.search) {	
				
				searchResults = true;
				instance.searchCount = data.search.matches.length;
			
			}
			
			else {
				
				instance.searchCount = 0;
				
			}
			
			instance.showWhichResults();
			
			if(readResults) {
				
				instance.readResults(data.read);
				
			}
			
			if(searchResults) {
			
				instance.searchResults(data.search);
				
			}
						
			instance.loading = false;
			
			instance.initToolTip();
			
		},
		
		error: function() {
		
		}

	});

}

Bible.prototype.backButtonHandler = function(type) {
	
	//return;
	
	//console.log(type);
	
	//console.log(type);
	//console.log(this.settings.parentContainer);
	
	//console.log(this.topVerse+' '+this.currentSearchQuery);
	
	switch(type) {
		
		case 'read':
		
			$(this.settings.parentContainer+' img.back-button[type=read]').css({display: 'block'});
			$(this.settings.parentContainer+' img.back-button[type=search]').css({display: 'none'});
			
			//$(this.settings.inputField).val(this.currentSearchQuery);
		
			break;
			
		case 'search':
				
			$(this.settings.parentContainer+' img.back-button[type=read]').css({display: 'none'});
			$(this.settings.parentContainer+' img.back-button[type=search]').css({display: 'block'});
		
			//$(this.settings.inputField).val(this.topVerse);
		
			break;
		
		default: 
		
			$(this.settings.parentContainer+' img.back-button[type=read]').css({display: 'none'});
			$(this.settings.parentContainer+' img.back-button[type=search]').css({display: 'none'});

		
	}	
		
}

Bible.prototype.showWhichResults = function(type) {
	
	//console.log(type);
		
	if(type != 'search' && type != 'read') {
	
		if(this.searchCount > 0) {
			
			$(this.settings.readResults).css({display: 'none'});
			$(this.settings.searchResults).css({display: 'block'});
			$(this.settings.parentContainer+' div.search-result-header').css({display: 'block'});
			
			this.backButtonHandler('read');
			
		}
		
		else {
		
			$(this.settings.readResults).css({display: 'block'});
			$(this.settings.searchResults).css({display: 'none'});
			$(this.settings.parentContainer+' div.search-result-header').css({display: 'none'});
			
			this.backButtonHandler('search');
		
		}
	
	}
	
	else {
	
		if(type == 'search') {
			
			$(this.settings.readResults).css({display: 'none'});
			$(this.settings.searchResults).css({display: 'block'});
			$(this.settings.parentContainer+' div.search-result-header').css({display: 'block'});
			
			this.backButtonHandler('read');
			
		}
		
		else {
		
			$(this.settings.readResults).css({display: 'block'});
			$(this.settings.searchResults).css({display: 'none'});
			$(this.settings.parentContainer+' div.search-result-header').css({display: 'none'});
			
			this.backButtonHandler('search');
		
		}
	
	}
	
}

Bible.prototype.advancedSearchOptions = function(searchType) {
	
	this.settings.searchType = searchType;
	
	str = 	'<ul style="list-style:none;" class="advanced-search-options clearfix">'+
				
				'<li type="exactPhraseSearch" class="tooltip" title="Only matches the exact word or phrase&lt;br /&gt;\'seed\' matches \'seed\' NOT seeds">Exact</li>'+
				'<li type="containsPhraseSearch" class="tooltip" title="Matches any verse that contains these sequence of characters&lt;br /&gt;\'amen\' matches \'firmament\' and \'amen\'">Contains</li>'+
				'<li type="containsTheseWords" class="tooltip" title="Only matches verses that contain ALL of these exact words or phrases&lt;br /&gt; - Words or phrases must be separated by a comma&lt;br /&gt;ex: Jesus, Son of God">Contains These Exact Words</li>'+
			'</ul>';
	
	str += '<img class="analytics-icon tooltip" title="View Search Analytics" src="/images/icons/analytics.png" alt="Analytics" />';
	
	return str;
	
}

Bible.prototype.initToolTip = function() {
	
	$('.tooltip').tipTip({
					
		maxWidth: 'auto',
		edgeOffset: 5,
		defaultPosition: 'top'				
					
	});
	
}

Bible.prototype.getOppositeSide = function() {
		
	pattern = /\d$/;
	pane = pattern.exec(this.settings.inputField);
		
	pane = (parseInt(pane[0]) == 1) ? 2 : 1;
	
	return pane;
}

Bible.prototype.searchAnalytics = function(data) {
		
	str = 	'<div class="analytics">'+
				
				'<img class="close-analytics" src="/images/buttons/x-button.png" alt="Close" />'+
				
				'<h2 class="analytics-header">Search Results Analytics</h2>'+
				
				'<div class="analytics-pad a-cf" type="cf">'+
					
					'<p><span class="key">Search Query: </span>'+
					'<span class="value">'+this.currentSearchQuery+'</span></p>'+
				
					'<p><span class="key">First Mention: </span>'+
					'<span class="value">'+data.first.abbr+' '+data.first.chapter+':'+data.first.verse+'</span></p>'+
					'<p><span class="key">Last Mention: </span>'+
					'<span class="value">'+data.last.abbr+' '+data.last.chapter+':'+data.last.verse+'</span></p>'+
					'<div class="all-references">'+data.cross_references+'</div>'+
					'</div>'+
					
				'<div class="analytics-pad a-numbers" type="numbers">'+
					'<div class="testament-counts">'+
						'<p><span class="key">Old Testament: </span><span class="value">'+data.old_testament+' verses</span></p>'+
						'<p><span class="key">New Testament: </span><span class="value">'+data.new_testament+' verses</span></p>'+
					'</div>'+
					
					'<div class="all-books clearfix">';
				
	
					volume = 'Old Testament';
					
					str += '<div class="volume"><h3>Old Testament</h3>';
					
					for(i in data.books) {
						
						if(volume != data.books[i].volume) {
						
							volume = data.books[i].volume;
							str += '</div>';
							str += '<div class="volume"><h3>'+data.books[i].volume+'</h3>';
							
						}
						
						
						ct = (data.books[i].count < 1) ? '<span class="value" style="color:#999;">'+data.books[i].count+'</span>' : '<span class="value" style="font-weight:bold; color:#0099cc;">'+data.books[i].count+'</span>';
						
						str += '<p><span class="key">'+data.books[i].abbr+'</span>: '+ct+'</p>';												
					}
					
						str += '</div>';
					
					
	str +=			'</div>';				
				
	str +=		'</div>'+
				
			'</div>';
			
	$(this.settings.parentContainer).append(str);
	
}

Bible.prototype.searchResults = function(data) {
	
	var instance = this.self;
	times = '';

	arrowType = (this.getOppositeSide() == 1) ? 'left-arrow' : 'right-arrow' ;

	if(data.search_type != 'containsTheseWords') {
		times = '<span class="search-result-count">'+data.word_count+'</span> times';		
	}


	str = '<p class="search-result-header light-gray"><span class="search-query">"'+data.query+'"</span><br /> <span style="font-size:.89em; color:#333; padding-left:5px; font-style: italic;">Found '+times+' in '+data.total+' verses</span></span></p>';

	//add search settings button
	
	//str += '<img class="search-settings" src="/images/buttons/settings.png" alt="Settings" />';

	str += this.advancedSearchOptions(data.search_type);

	$(this.settings.parentContainer+' div.search-result-header').html(str);

	if(this.settings.searchTheme == 'default') {
	
		str = 	'<ul class="search-results">';
	
		$(data.matches).each(function(i) {
		
			str += 	'<li>'+
						'<span class="reference" reference="'+this.book+' '+this.chapter+':'+this.verse+'">'+this.book+' '+this.chapter+':'+this.verse+'</span> <span class="other-pane" reference="'+this.book+' '+this.chapter+':'+this.verse+'"><img class="tooltip" style="cursor:pointer; width:15px;" src="/images/buttons/'+arrowType+'.png" title="View On Other Side" alt="View On Other Side" /></span><br />'+
						'<p class="line">'+this.line+'</p>'+
					'</li>';
		})	
		
		str += '</ul>';
				
	}

	$(this.settings.searchResults).html(str);
	
	$(this.settings.searchResults).scrollTop(0);
	
	this.applySelectedSearchType();
	
	if(data.analysis != null) {
		
		this.searchAnalytics(data.analysis);
		
	}
	
	//attach Bible.jumpToVerse(reference) to Search Results
	
	$(this.settings.searchResults+' span.reference, '+this.settings.searchResults+' span.other-pane').click(function() {	
		
		elementClass = $(this).attr('class');
		inputField = instance.settings.inputField;
		
		if(elementClass == 'other-pane') {
		
			if(instance.getOppositeSide() == 1) {
				bible.preserveSearchResults = 1;
				bible.get($(this).attr('reference'));
			}
			
			else {
				bible2.preserveSearchResults = 1;
				bible2.get($(this).attr('reference'));
			}
				
			return;
		
		}
		
		instance.jumpToVerse( $(this).attr('reference'), inputField );		
	
	})
	
},

Bible.prototype.readResults = function(data) {
	
	var instance = this.self;
		
	str = '';
	
	if(this.settings.readTheme == 'verse') {
				
		book = '';
		chapter = '';
				
		$(data.scripture).each(function(i) {
			
			if((this.chapter != chapter || this.chapter == 1 && this.book != book ) && this.verse == 1) {
				
				str += '<h2>'+this.book+' '+this.chapter+'</h2>';
				book = this.book;
				chapter = this.chapter;
				
			}
			
			str += 	'<p>'+
						'<span bible_id="'+this.id+'" class="reference" reference="'+this.book+' '+this.chapter+':'+this.verse+'">'+
							this.verse+
						'</span> '+ 
						'<span class="line">'+this.line+'</span>'
					'</p>';
		})
	
	}
	
	if(data.direction == 'up') {
										
		$(this.settings.readResults).prepend(str);
		
		this.setStartAndLastVerse();
		this.goto(this.currentReference);
	
	}
	
	if(data.direction == 'down') {
	
		$(this.settings.readResults).append(str);
		
		this.setStartAndLastVerse();
		this.goto(this.currentReference);
	
	}
	
	if(data.direction == 'both') {
	
		$(this.settings.readResults).html(str);
					
		this.setStartAndLastVerse();				
		this.goto(this.currentReference, true);
	
	}
	
	
		
}

