$(document).ready(function() {
	// GLOBALS
	var main = $("#main");
	var page = $("#page");
	var pagewidth = page.outerWidth();
	var increment = pagewidth+10;
	
	// Subject to change (window resize)
	// so these should be recalculated onLoad and on resize
	var fullwidth = (page.attr("offsetWidth") > page.attr("scrollWidth")) ? page.attr("offsetWidth") : page.attr("scrollWidth");
	fullwidth = fullwidth - increment;
	var tot_pages = Math.ceil(fullwidth/increment);
	
	// Now we set the hidden variables
	$('#current_page').val(1);
	$('#increment').val(increment);
	$('#total_pages').val(tot_pages);
	// If the html has a class for pgheader, make it its own page
	$(".pgheader").addClass("pageheight");
	
	// Dealing with the article contents
	var article = document.getElementById("main");
	// Cleaning it
	clearLinks(article);
	cleanStyles(article);					// Removes all style attributes
	// article = killDivs(article);				// Goes in and removes DIVs that have more non <p> stuff than <p> stuff
	article = killBreaks(article);            // Removes any consecutive <br />'s into just one <br /> 
	article = convertEntities(article);
	
	// Remove all inline style tags
	var styleTags = document.getElementsByTagName("style");
	for (var j=0;j < styleTags.length; j++) {
		if (navigator.appName != "Microsoft Internet Explorer") {
			styleTags[j].textContent = "";
		}
	}
	
	// This makes sure there are no scrollbars by adjusting the height of the "main" div based on the browser window
	var minorOffset = (document.all)? 50 : 100;
	
	function setHgt() {
		// This function gets called every time the browser window gets resized, and onload
		var sHGT;
		var oldfullwidth = fullwidth;
		var newfullwidth = (page.attr("offsetWidth") > page.attr("scrollWidth")) ? page.attr("offsetWidth") : page.attr("scrollWidth");
		fullwidth = newfullwidth - increment;
		
		// Get height of the main container
		srcobj=document.getElementById('main');
		if (self.innerHeight)	{
			sHGT = self.innerHeight;
		} else { 
			if (document.documentElement && document.documentElement.clientHeight) {
				sHGT = document.documentElement.clientHeight;
			} else {
				if (document.body) {
              sHGT = document.body.clientHeight;
				}
			}
		}
		
    	sHGT=sHGT-(document.getElementById('main').offsetTop+minorOffset);
		
		// Set the heights of the main, left and right button containers
	  	document.getElementById('main').style.height=sHGT+"px";
		document.getElementById('left').style.height=sHGT+"px";
		document.getElementById('right').style.height=sHGT+"px";
		
		// This is to make an element with class .pgheight the height of a page
		// Basically a clear
		var pghgt = sHGT - 10;
		$('.pageheight').height(pghgt);
		
		// This makes the middle container bigger
		var middleOffset = sHGT+55;
		document.getElementById('middle').style.height=middleOffset+"px";
		
		var curPage = parseInt($('#current_page').val());
		
		var newCurPage = Math.ceil(Math.abs((newfullwidth * curPage)/oldfullwidth));

		curPage = newCurPage;
		
		// Draw pagination indicator
		var new_tot_pages = Math.ceil(newfullwidth/increment);
		$("#totalPages").html(new_tot_pages);
		$("#currentPage").html(newCurPage);
		$("#current_page").val(newCurPage);
		
		// This loop draws the pagination
		var pagination_html = '';
		
		for (var p=1; p<= new_tot_pages; p++) {
			if (p == newCurPage) {
				pagination_html += '<a class="page_link active_page" href="javascript:pageTo(' + p +')" longdesc="' + p +'">&nbsp;</a>';
			} else {
				pagination_html += '<a class="page_link" href="javascript:pageTo(' + p +')" longdesc="' + p +'">&nbsp;</a>';
			}
		}

		$('#page_indicator').html(pagination_html);

	}

	
	$('.nextbtn').click(function() {advance();});
	$('.prevbtn').click(function() {goBack();});
	// This handles the keypresses
	$(document).keydown(function (e) {
		//Next
		//if the keyCode or charCode is 39 (right arrow)
		if (e.keyCode == 39 || e.charCode == 39 ){
			advance();
			document.getElementById('right').style.background='url(http://reader.redub.org/newreader/images/rightbtn_over.png) repeat-y';
		}
		//Previous
		//works exactly as the above example but for the left arrow (37)
		if (e.keyCode == 37 || e.charCode == 37){
			goBack();
			document.getElementById('left').style.background='url(http://reader.redub.org/newreader/images/leftbtn_over.png) repeat-y';
		}
	});
	$(document).keyup(function (e) {
		//Next
		//if the keyCode or charCode is 39 (right arrow)
		if (e.keyCode == 39 || e.charCode == 39 ){
			document.getElementById('right').style.background='url(http://reader.redub.org/newreader/images/rightbtn_off.png) repeat-y';
		}
		//Previous
		//works exactly as the above example but for the left arrow (37)
		if (e.keyCode == 37 || e.charCode == 37){
			document.getElementById('left').style.background='url(http://reader.redub.org/newreader/images/leftbtn_off.png) repeat-y';
		
		}
	});
	
	
	window.onload=setHgt;
	window.onresize=setHgt;
	$("#runninghead").css("margin-top", "0");
	$("#main").css("top", "0");
	$(".loading").css("display", "none");
});

function goBack(){
	new_page = parseInt($('#current_page').val())-1;
	//if there is an item before the current active link run the function
	if($('.active_page').prev('.page_link').length==true){
		pageTo(new_page);
	}

}

function advance(){
	new_page = parseInt($('#current_page').val()) + 1;
	//if there is an item after the current active link run the function
	if($('.active_page').next('.page_link').length==true){
		pageTo(new_page);
	}

}

function pageTo(page_num) {
	curPage = parseInt($('#current_page').val());
	var inc = parseInt($('#increment').val());
	var newLeft= inc-(inc*page_num);
	/*get the page link that has longdesc attribute of the current page and add active_page class to it
	and remove that class from previously active page link*/
		$('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');
		$("#main").animate( { left: newLeft }, 500);
		$("#currentPage").html(page_num);
		$("#current_page").val(page_num);
}
