///////////////////////////////////////////////////
///////// Global vars
///////////////////////////////////////////////////
var currentZoomNew = "1";
var isLoadingL = false;
var isLoadingR = false;
var isWorking = false;
var contentsCreated = 'false';
var contentsListObjects = Object;
var currentSection = '';

//isset for javascript
function isset(varname){
  return(typeof(varname)!='undefined');
}

///////////////////////////////////////////////////
///////// IE6 and lower rules
///////////////////////////////////////////////////

function drawPageArea(fullScreen){  // Get real width and height of window even if this is only being used by IE.
	var myWidth = 0, myHeight = 0;
	if( typeof window.innerWidth == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}

	// Get Page Area correct
	if (fullScreen == "fullscreen") {	// if called by the fullsreen fcn, use whole page area.
		var iePageArea = $("page-area");
		iePageArea.style.width = myWidth + "px";
		iePageArea.style.height = myHeight + "px";
		
		if(iePageArea !== null) {
		iePageArea = $("overlay");
		iePageArea.style.width = myWidth + "px";
		iePageArea.style.height = myHeight + "px"; }
		if(iePageArea !== null) {
		iePageArea = $("page-area-hide");
		iePageArea.style.width = myWidth + "px";
		iePageArea.style.height = myHeight + "px"; }
		
	} else if (fullScreen != "fullscreen") {
		iePageArea = $("page-area");
		iePageArea.style.width = (myWidth - "222") + "px";
		iePageArea.style.height = (myHeight - "125") + "px";

		iePageArea = $("overlay");
		if(iePageArea !== null) {
		iePageArea.style.width = (myWidth - "222") + "px";
		iePageArea.style.height = (myHeight - "125") + "px"; }
		iePageArea = $("page-area-hide");
		if(iePageArea !== null) {
		iePageArea.style.width = (myWidth - "222") + "px";
		iePageArea.style.height = (myHeight - "125") + "px";}
	}

	// Get rhs nav bar correct
	var ieRhs = $("rhs");
	ieRhs.style.height = (myHeight - "125") + "px";
	
	// Get contents/function area correct
	var ieSidebarBottom = parseFloat($("sidebar").getStyle('bottom'));

	if (document.compatMode && document.all) {	//sniff for IE 6
		$("sidebar").style.height = (myHeight - "125" - "41" - ieSidebarBottom - 1) + "px";
	} else {
		$("sidebar").style.height = (myHeight - "125" - "63" - ieSidebarBottom - 1) + "px";
		$("sidebar").style.bottom = ieSidebarBottom + "px";
	}
	
	return true;
}


//call it on resize
if(isset(window.isIE6)) {window.onresize = drawPageArea;}

///////////////////////////////////////////////////
///////// Drag Scrollable
///////////////////////////////////////////////////
var DragScrollable = Class.create();
DragScrollable.prototype = {
	initialize: function(element) {
		this.element = $(element);
		this.active = false;
		this.scrolling = false;

		if (document.compatMode && document.all) { //sniff for ie 6+
			this.element.style.cursor = 'pointer';
		} else {
			this.element.style.cursor = 'hand';
		}

		this.eventMouseDown = this.startScroll.bindAsEventListener(this);
		this.eventMouseUp = this.endScroll.bindAsEventListener(this);
		this.eventMouseMove = this.scroll.bindAsEventListener(this);
		this.eventdblclk = this.dblclk.bindAsEventListener(this);

		Event.observe(this.element, 'mousedown', this.eventMouseDown);
		Event.observe(this.element, 'dblclick', this.eventdblclk);
		// Add new elements to dom for imageChange()
		ReportCast.initLoading();

	},
	destroy: function() {
		Event.stopObserving(this.element, 'mousedown', this.eventMouseDown);
		Event.stopObserving(document, 'mouseup', this.eventMouseUp);
		Event.stopObserving(document, 'mousemove', this.eventMouseMove);
	},
	dblclk: function(event) {
		if (event.shiftKey == 1) {
			ReportCast.zoomOutNew();
		} else {
			ReportCast.zoomInNew();
		}

	},
	startScroll: function(event) {
		this.startX = Event.pointerX(event);
		this.startY = Event.pointerY(event);
		if (Event.isLeftClick(event) && (this.startX < this.element.offsetLeft + this.element.clientWidth) && (this.startY < this.element.offsetTop + this.element.clientHeight)) {
			this.element.style.cursor = 'move';
			Event.observe(document, 'mouseup', this.eventMouseUp);
			Event.observe(document, 'mousemove', this.eventMouseMove);
			this.active = true;
			Event.stop(event);
		}
	},
	endScroll: function(event) {

		if (document.compatMode && document.all) { //sniff for ie 6+
			this.element.style.cursor = 'pointer';
		} else {
			this.element.style.cursor = 'hand';
		}

		this.active = false;
		Event.stopObserving(document, 'mouseup', this.eventMouseUp);
		Event.stopObserving(document, 'mousemove', this.eventMouseMove);
		Event.stop(event);
	},
	scroll: function(event) {
		if (this.active) {
			this.element.scrollTop += (this.startY - Event.pointerY(event));
			this.element.scrollLeft += (this.startX - Event.pointerX(event));
			this.startX = Event.pointerX(event);
			this.startY = Event.pointerY(event);
		}
		Event.stop(event);
	}

};

///////////////////////////////////////////////////
///////// effect.scroll
///////////////////////////////////////////////////
Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
	initialize: function(element) {
		this.element = $(element);
		var options = Object.extend({
			x: 0,
			y: 0,
			mode: 'absolute'
		},
		arguments[1] || {});
		this.start(options);
	},
	setup: function() {
		if (this.options.continuous && !this.element._ext) {
			this.element.cleanWhitespace();
			this.element._ext = true;
			this.element.appendChild(this.element.firstChild);
		}

		this.originalLeft = this.element.scrollLeft;
		this.originalTop = this.element.scrollTop;

		if (this.options.mode == 'absolute') {
			this.options.x -= this.originalLeft;
			this.options.y -= this.originalTop;
		} else {

}
	},
	update: function(position) {
		this.element.scrollLeft = this.options.x * position + this.originalLeft;
		this.element.scrollTop = this.options.y * position + this.originalTop;
	}
});

///////////////////////////////////////////////////
///////// non-ajax get new image
///////////////////////////////////////////////////
ReportCast = {
	postload: function() { //Agressive postload

		var postloadImages = [];
		
		//alert("currentPageLeft: "+currentPageLeft);
		
		if((parseFloat(currentPageLeft) +2 > 0) && (parseFloat(currentPageLeft) +2 <= pageTotal)) {
			postloadImages[currentPageLeft] = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + (parseFloat(currentPageLeft) + 2) + "&zoom=" + currentZoomNew;
		}
		if((parseFloat(currentPage)  +2 > 0) && (parseFloat(currentPage) +2 <= pageTotal)) {
			postloadImages[currentPage] = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + (parseFloat(currentPage) + 2) + "&zoom=" + currentZoomNew;
		}

		postloadImages.each(function(elm){
			var postloadPath = elm;
			var postloadNew = new Image();
			postloadNew.setAttribute('src',postloadPath);
		});
	},
	changeLeft: function(ExistingImageIDRight, ImageURLRight, ExistingImageIDLeft, ImageURLLeft) {
		//Get Image Left
		var TheImageLeftContainer = $(ExistingImageIDLeft);
		//Swap Image Left
		var TheImageLeftTemp = new Image();
		TheImageLeftTemp.onload = function() {
			$('preloader-image-l').src = ImageURLLeft;
			var TheImageLeft = document.createElement('img');
			TheImageLeft.onload = function(evt) {
				TheImageLeftContainer.src = this.src;
				isLoadingL = false;
				ReportCast.isLoading(ExistingImageIDRight, ImageURLRight);
			};
			TheImageLeft.src = ImageURLLeft;
			TheImageLeftTemp.onload = function() {}; //	clear onLoad, IE behaves irratically with animated gifs otherwise 
		};
		TheImageLeftTemp.src = ImageURLLeft;
	},
	changeRight: function(ExistingImageIDRight, ImageURLRight, ExistingImageIDLeft, ImageURLLeft) {
		//Get Image Right
		var TheImageRightContainer = $(ExistingImageIDRight);
		//Swap Image Right
		var TheImageRightTemp = new Image();
		TheImageRightTemp.onload = function() {
			$('preloader-image-r').src = ImageURLRight;
			var TheImageRight = document.createElement('img');
			TheImageRight.onload = function(evt) {
				TheImageRightContainer.src = this.src;
				isLoadingR = false;
				ReportCast.isLoading();
			};
			TheImageRight.src = ImageURLRight;
			TheImageRightTemp.onload = function() {}; //	clear onLoad, IE behaves irratically with animated gifs otherwise 
		};
		TheImageRightTemp.src = ImageURLRight;
	},
	//////////////////////////////////
	// Change Images
	changeImage: function(ExistingImageIDLeft, ImageURLLeft, ExistingImageIDRight, ImageURLRight, page_scale, page_width_current, page_height_current) {

		if (useTransitions == false) {

			$(ExistingImageIDLeft).setStyle({ width: Math.round(page_scale / 100 * page_width_current) + 'px', height: Math.round(page_scale / 100 * page_height_current) + 'px'});
			$(ExistingImageIDRight).setStyle({ width: Math.round(page_scale / 100 * page_width_current) + 'px', height: Math.round(page_scale / 100 * page_height_current) + 'px'});

		} else if (useTransitions == true) {

			//Scale original image 
			(new Effect.Scale(ExistingImageIDLeft, page_scale, {
			scaleMode: {
				originalWidth: page_width_current,
				originalHeight: page_height_current
			},
			scaleFromCenter: false,
			duration: 0.5
			}));

			(new Effect.Scale(ExistingImageIDRight, page_scale, {
			scaleMode: {
				originalWidth: page_width_current,
				originalHeight: page_height_current
			},
			scaleFromCenter: false,
			duration: 0.5
			}));

		} // end if useTransitions

		// show loading bar
		Element.show('loading');
		isLoadingL = true;
		isLoadingR = true;

		ReportCast.changeLeft(ExistingImageIDRight, ImageURLRight, ExistingImageIDLeft, ImageURLLeft);

		ReportCast.changeRight(ExistingImageIDRight, ImageURLRight, ExistingImageIDLeft, ImageURLLeft);

		// SET WIDTH OF IMAGE AREA TO BE SCROLLED
		
		if (useTransitions == false) {
			if (page_scale <= 100) { // decrease container slower than images when reducing
				setTimeout(function() {
					$('image-area').setStyle({ width: page_scale / 100 * (Math.round(page_width_current) * 2 + 12) + 'px'});
				}, 50);
			} else if (page_scale >= 100) { // increase container faster than images when enlarging
				setTimeout(function() {
					$('image-area').setStyle({ width: page_scale / 100 * (Math.round(page_width_current) * 2 + 12) + 'px'});
				}, 0);
			}
		} else if (useTransitions == true) {
			if (page_scale <= 100) { // decrease container slower than images when reducing

				(new Effect.Scale('image-area', page_scale, {
				scaleY: false,
				scaleMode: {
					originalWidth: Math.round(page_width_current * 2 + 12)
				},
				//queue: 'front',
				duration: 0.7
				}));

			} else if (page_scale >= 100) { // increase container faster than images when enlarging

				(new Effect.Scale('image-area', page_scale, {
				scaleY: false,
				scaleMode: {
					originalWidth: Math.round(page_width_current * 2 + 11)
				},
				//queue: 'front',
				duration: 0.3
				}));
			}
	
		}

	},

	///////////////////////////////////////////////////
	// Check if either image is loading, remove loading image if not.
	///////////////////////////////////////////////////
	isLoading: function(ExistingImageIDLeft, ImageURLLeft, ExistingImageIDRight, ImageURLRight, page_scale, page_width_current, page_height_current) {
		if (isLoadingL === true) { // reload the rhs image
		} else if (isLoadingR === true) {} else { //neither are loading any more
			Element.hide('loading'); // hide loading bar once image is preloaded
			ReportCast.postload();
		}
	},

	///////////////////////////////////////////////////
	// Prev Page
	///////////////////////////////////////////////////
	pagePrev: function() {
		if(isWorking == "true") {return false;} else {isWorking="true";setTimeout(function(){isWorking="false";}, 550);} //disables button for specified time

		var PageTempLeft = parseFloat(currentPageLeft) - 2;
		var PageTempRight = parseFloat(currentPage) - 2;

		ReportCast.closeSidebars();

		return ReportCast.pageCheck(PageTempLeft, PageTempRight);
	},

	///////////////////////////////////////////////////
	// Next Page
	///////////////////////////////////////////////////
	pageNext: function() {
		if(isWorking == "true") {return false;} else {isWorking="true";setTimeout(function(){isWorking="false";}, 550);} //disables button for specified time

		var PageTempLeft = parseFloat(currentPageLeft) + 2;
		var PageTempRight = parseFloat(currentPage) + 2;
		ReportCast.closeSidebars();

		return ReportCast.pageCheck(PageTempLeft, PageTempRight);
	},

	///////////////////////////////////////////////////
	// Page Checks
	///////////////////////////////////////////////////
	pageCheck: function(goToPageLeft, goToPageRight) {
		if (goToPageLeft == null) {
			return false;
		} // IF NO PAGES SENT, RETURN NONE
		else if (goToPageLeft < 0) { // IF BEFORE ZERO, RETURN FIRST PAGE
			currentPageLeft = 0;
			currentPage = 1;
		} else if (goToPageLeft > parseFloat(pageTotal)) { // IF AFTER DOC FINISHES, RETURN LAST PAGE
			var numOddEven = parseFloat(pageTotal) % 2;
			if (numOddEven == 0) {
				currentPageLeft = parseFloat(pageTotal);
				currentPage = parseFloat(pageTotal) + 1;
			} else if (numOddEven == 1) {
				currentPageLeft = parseFloat(pageTotal) - 1;
				currentPage = parseFloat(pageTotal);
			}
		} else if (goToPageRight == null) { // IF ONLY ONE PAGE REQUESTED, RETURN PAGE WITH CORRESPONDING SPREAD
			numOddEven = parseFloat(goToPageLeft) % 2;
			if (numOddEven == 0) { // will always return 0 if num is even
				currentPageLeft = goToPageLeft;
				currentPage = parseFloat(goToPageLeft) + 1;
			} else if (numOddEven == 1) {
				currentPageLeft = parseFloat(goToPageLeft) - 1;
				currentPage = goToPageLeft;
			}
		} else { // IF PAGES SENT AS NORMAL, RETURN PAGES
			currentPageLeft = goToPageLeft;
			currentPage = goToPageRight;
		}
		ReportCast.ajaxBookmark();
		return false;
	},

	///////////////////////////////////////////////////
	// Page Specific
	///////////////////////////////////////////////////
	pageSpecific: function(goToPageLeft, goToPageRight) {
		return ReportCast.pageCheck(goToPageLeft, goToPageRight);
	},

	///////////////////////////////////////////////////
	// Remove border on page 0 and < pageTotal
	///////////////////////////////////////////////////
	noBorder: function(side) {
		var side;
		
		if(side == "left" || side == "") {
			$("page-image-l").addClassName("no-border");
		} else if(side == "right") {
			$("page-image-r").addClassName("no-border");
		} else if(side == "cancel") {
			$("page-image-l").removeClassName("no-border");
			$("page-image-r").removeClassName("no-border");

		}

	},

	///////////////////////////////////////////////////
	// Full Screen 
	///////////////////////////////////////////////////
	fullScreen: function() {
		if(isWorking == "true") {return false;} else {isWorking="true";setTimeout(function(){isWorking="false";}, 850);} //disables button for specified time
	
		// Hide thumbnails if visible.
		var thumbsVisible = $('overlay');
		if (thumbsVisible !== null) {		
			if(thumbsVisible.hasClassName('hidden') == false) { // exists and isn't hidden, then...
				$(thumbsVisible).toggleClassName('hidden');
				$('page-area-hide').toggleClassName('hidden');
			}
		}

		$('page-area').morph({ right: '0px', top: '0px'}, { duration: 0.8 });
//		if($('overlay')) {$('overlay').morph({ right: '0px', top: '0px'}, { duration: 0.8 }); }
//		if($('page-area-hide')) {$('page-area-hide').morph({ right: '0px', top: '0px'}, { duration: 0.8 }); }
		$('controls').morph({ top: '-23px', right: '-44px', height: '72px'}, { duration: 0.8 });
		$('loading').morph({ top: '5px'}, { duration: 0.8 });
		$('header').morph({ height: '0px'}, { duration: 0.8 });
		$('rhs').morph({ right: '-222px'}, { duration: 0.8 });

		$('control-page', 'control-zoom', 'control-view').invoke('hide');

		//CHANGE BUTTON TO FULLSCEEN REVERT
		var viewTemp = $('control-view-full');
		viewTemp.writeAttribute({
			title: "Close Fullscreen View"
		});
		viewTemp.onclick = function() {
			return ReportCast.fullScreenRevert();
		};
		viewTemp.addClassName('revert');
		$('controls').addClassName('fullscreen');
		if($('overlay')) {$('overlay').addClassName('fullscreen');}

		//Change IE resize
		if(isset(window.isIE6)) {drawPageArea('fullscreen');window.onresize = function() {drawPageArea('fullscreen');};}

		return false;
	},

	fullScreenRevert: function() {
		if(isWorking == "true") {return false;} else {isWorking="true";setTimeout(function(){isWorking="false";}, 850);} //disables button for specified time

		$('page-area').morph({ right: '222px', top: '125px'}, { duration: 0.8 });
//		if($('overlay')) {$('overlay').morph({ right: '222px', top: '125px'}, { duration: 0.8 }); }
//		if($('page-area-hide')) {$('page-area-hide').morph({ right: '222px', top: '125px'}, { duration: 0.8 }); }
		$('controls').morph({ top: '25px', right: '222px', height: '94px'}, { duration: 0.8 });
		$('loading').morph({ top: '130px'}, { duration: 0.8 });
		$('header').morph({ height: '119px'}, { duration: 0.8 });
		$('rhs').morph({ right: '0px'}, { duration: 0.8 });

		$('control-page', 'control-zoom', 'control-view').invoke('show');

		//CHANGE BUTTON TO FULLSCEEN 
		var viewTemp = $('control-view-full');
		viewTemp.writeAttribute({
			title: "Fullscreen View"
		});
		viewTemp.onclick = function() {
			return ReportCast.fullScreen();
		};

		viewTemp.removeClassName('revert');
		$('controls').removeClassName('fullscreen');
		if($('overlay')) {$('overlay').removeClassName('fullscreen');}

		//Change IE resize BACK
		if(isset(window.isIE6)) {setTimeout(drawPageArea, 800);window.onresize = drawPageArea;}

		return false;
	},

	///////////////////////////////////////////////////
	// when zoom in is clicked
	///////////////////////////////////////////////////
	zoomInNew: function() {
		var zoomTemp = parseFloat(currentZoom) + 1;
		if (zoomTemp === "") {
			return false;
		}
		if (zoomTemp === 0) {
			return false;
		}
		if (zoomTemp == 4) {
			return false;
		}

		currentZoomNew = zoomTemp;

		ReportCast.ajaxBookmark();

		return false;
	},

	///////////////////////////////////////////////////
	// when zoom out is clicked
	///////////////////////////////////////////////////
	zoomOutNew: function() {
		var zoomTemp = currentZoom - 1;

		if (zoomTemp === "") {
			return false;
		}
		if (zoomTemp === 0) {
			return false;
		}
		if (zoomTemp == 4) {
			return false;
		}

		currentZoomNew = zoomTemp;

		ReportCast.ajaxBookmark();

		return false;
	},

	///////////////////////////////////////////////////
	// Zoom to level.
	///////////////////////////////////////////////////
	zoomSpecific: function(goToLevel) {
		var zoomTemp = goToLevel;

		if (zoomTemp === "") {
			return false;
		}
		if (zoomTemp < 1) {
			return false;
		}
		if (zoomTemp > 3) {
			return false;
		}

		currentZoomNew = zoomTemp;

		ReportCast.ajaxBookmark();

		return false;
	},

	///////////////////////////////////////////////////
	// CHANGE ADDRESS BAR AND TRIGGER UPDATE
	///////////////////////////////////////////////////
	ajaxBookmark: function(refresh) {

		// Get current URL minus the bookmark
		var docURL = window.location.href.split("#")[0];

		// Get scroll levels
		var scrOfX = 0,
		scrOfY = 0;

		var area = document.getElementById("page-area");
		scrOfX = area.scrollLeft;
		scrOfY = area.scrollTop;

		var randRefresh = "";
		if (refresh == "refresh") {
			var d = new Date();
			randRefresh = "|" + d.getMilliseconds();
		}

		// Set the bookmark
		var functionReturn = "p=" + currentPage + "|z=" + currentZoomNew + "|sx=" + scrOfX + "|sy=" + scrOfY + randRefresh;

		// Hide thumbs if visible
		var thumbsVisible = $('overlay');
		if (thumbsVisible !== null) {		
			//Element.hide('overlay');
			//Element.hide('page-area-hide');
			thumbsVisible.addClassName('hidden');
			$('page-area-hide').addClassName('hidden');
		}


		//Return the new location
		unFocus.History.addHistory(functionReturn);

	},

	appenedElem: function(whatever) {
		$('header-upper').insert({
			before: whatever + "&nbsp;&nbsp;|&nbsp;&nbsp;"
		});
	},
	///////////////////////////////////////////////////
	// AJAX HISTORY
	///////////////////////////////////////////////////
	ajaxHistory: function() {

		this.historyListener = function(historyHash) {

			if (historyHash === "") {
				return false;
			}

			////////////////////////////////////////////////////////
			// Get current HASH and get variable pairs
			var hashArray = historyHash.split("|");

			for (i = 0; i < hashArray.length; i++) {
				var hashTemp = hashArray[i].split("=");

				if (hashTemp[0] == "p") {
					var new_page = hashTemp[1];
				}
				if (hashTemp[0] == "z") {
					var currentZoomNew = hashTemp[1];
				}
				if (hashTemp[0] == "sx") {
					var new_scrollx = hashTemp[1];
				}
				if (hashTemp[0] == "sy") {
					var new_scrolly = hashTemp[1];
				}
			}

			////////////////////////////////////////////////////////
			// Zoom
			// Get new zoom factor
			// Get current zoom factor
			var currentZoomScale;
			if (currentZoom == "1") {
				currentZoomScale = zoom1;
			} else if (currentZoom == "2") {
				currentZoomScale = zoom2;
			} else if (currentZoom == "3") {
				currentZoomScale = zoom3;
			} else {
				currentZoomScale = zoom1;
			}

			//alert("currentZoomScale  "+currentZoomScale);
			var currentZoomNewScale;
			if (currentZoomNew == "1") {
				currentZoomNewScale = zoom1;
			} else if (currentZoomNew == "2") {
				currentZoomNewScale = zoom2;
			} else if (currentZoomNew == "3") {
				currentZoomNewScale = zoom3;
			} else {
				currentZoomNewScale = zoom1;
			}
			//alert("currentZoomNewScale  "+currentZoomNewScale);

			// Set new Zoom level for images
			//currentZoomNew = new_zoom;
			////////////////////////////////////////////////////////
			// Page
			page_new_left = new_page - 1;
			page_new_right = new_page;

			// remove page border if on page 0 or < $pageTotal 
			if(page_new_left == 0) {
				ReportCast.noBorder('left');
			} else if(page_new_right >= pageTotal) {
				ReportCast.noBorder('right');
			} else {
				ReportCast.noBorder('cancel');
			}

			////////////////////////////////////////////////////////
			// Page sizes
			// Get current page dimensions
			page_width_current = Math.round(imageWidth * currentZoomScale);
			page_height_current = Math.round(imageHeight * currentZoomScale);

			// Get new page dimensions
			page_width_new = Math.round(imageWidth * currentZoomNewScale);
			page_height_new = Math.round(imageHeight * currentZoomNewScale);
			
			
			////////////////////////////////////////////////////////
			// Page Scale
			page_scale = page_width_new / page_width_current * 100;
			//alert("page_scale  "+page_scale);
			//alert("page_scale=page_width_new ("+page_width_new+") / page_width_current ("+page_width_new+") * 100");
			////////////////////////////////////////////////////////
			// Change image
			var pageUrlLeft = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + page_new_left + "&zoom=" + currentZoomNew;
			var pageUrlRight = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + page_new_right + "&zoom=" + currentZoomNew;

			//	var pageUrlLeft_next = fileIncludeURI+"page.php?orgPrefix="+orgPrefix+"&docPrefix="+docPrefix+"&page="+(page_new_left+1)+"&zoom="+currentZoomNew;
			//	var pageUrlRight_next = fileIncludeURI+"page.php?orgPrefix="+orgPrefix+"&docPrefix="+docPrefix+"&page="+(page_new_right+1)+"&zoom="+currentZoomNew;
			//		var tid;
			//		tid = setTimeout ( "ReportCast.changeImage('page-image-l', "+pageUrlLeft+", 'page-image-r', "+pageUrlRight+", "+page_scale+", "+page_width_current+", "+page_height_current+")", 100 );
			ReportCast.changeImage('page-image-l', pageUrlLeft, 'page-image-r', pageUrlRight, page_scale, page_width_current, page_height_current);


			// Stats - count image
			ReportCast.stats("Page "+page_new_left);
			setTimeout(function(){ReportCast.stats('Page '+page_new_right);},2000);

			////////////////////////////////////////////////////////
			// Scroll to appropriate place
			//alert("currentZoom   "+currentZoom);
			//alert("currentZoomNew   "+currentZoomNew);
			if (currentZoom == currentZoomNew) { // if only changing page, don't resize
			} else {


				var prevTop = new_scrolly;
				//alert("prevTop   "+prevTop);
				var prevLeft = new_scrollx;
				//alert("prevLeft   "+prevLeft);
				var prevPageHeight = page_height_current;
				//alert("prevPageHeight   "+prevPageHeight);
				var prevPageWidth = page_width_current;
				//alert("prevPageWidth   "+prevPageWidth);
				var newPageHeight = page_height_new;
				//alert("newPageHeight   "+newPageHeight);
				var newPageWidth = page_width_new;
				//alert("newPageWidth   "+newPageWidth);
				var deltaPageHeight = page_height_new - page_height_current; //assumes zoom in
				//alert("deltaPageHeight   "+deltaPageHeight);
				var deltaPageWidth = page_width_new - page_width_current;
				//alert("deltaPageWidth   "+deltaPageWidth);
				var newTop = parseFloat(new_scrolly) + (deltaPageHeight / 2);
				//alert("newTop   "+newTop);
				var newLeft = parseFloat(new_scrollx) + parseFloat(deltaPageWidth); //two pages, therefore I need 2x the difference in width. Technically (deltaPageWidth / 2) * 2.
				//alert("newLeft   "+newLeft);
				//Keep image in centre of display

				if (useTransitions == false) {

					$('page-area').scrollTop = newTop;
					$('page-area').scrollLeft = newLeft;

				} else if (useTransitions == true) {

					(new Effect.Scroll('page-area', {
						x: newLeft,
						y: newTop,
						duration: 0.5
					}));

				}
			}

			////////////////////////////////////////////////////////
			// Set new defaults
			currentZoom = currentZoomNew;
			currentPageLeft = page_new_left;
			currentPage = page_new_right;

			////////////////////////////////////////////////////////
			// ZOOM (formally zoomSpecific)

			// Remove old classes
			$$('#control-zoom-level a').invoke('removeClassName', 'current');
			$('control-zoom-in').removeClassName('na');
			$('control-zoom-out').removeClassName('na');

			// Add 'current' class to current zoom indicator
			var zoomIndicator = $('control-zoom-level-' + currentZoom);
			zoomIndicator.addClassName('current');

			//add classes for turning the buttons off
			if (currentZoom == 3) {
				var zoomButtonOff = $('control-zoom-in');
				zoomButtonOff.addClassName('na');
			}
			if (currentZoom == 1) {
				zoomButtonOff = $('control-zoom-out');
				zoomButtonOff.addClassName('na');
			}

			////////////////////////////////////////////////////////
			// Page (formally pageSpecific)
			// Remove old 'na' class
			$('control-page-prev').removeClassName('na');
			$('control-page-next').removeClassName('na');

			//add classes for turning the buttons off
			if (currentPageLeft <= 0) {
				var pageButtonOff = $('control-page-prev');
				pageButtonOff.addClassName('na');
			}
			if (currentPage >= parseFloat(pageTotal)) {
				pageButtonOff = $('control-page-next');
				pageButtonOff.addClassName('na');
			}

			// Adds current page numbers to the page number box
			if (currentPageLeft == "0") {
				var PageTempAttr = 'Page ' + currentPage + ' // Skip to page';
				var PageTempDisplay = currentPage;
			} else if (currentPage > parseFloat(pageTotal)) {
				PageTempAttr = 'Page ' + parseFloat(pageTotal) + ' // Skip to page';
				PageTempDisplay = parseFloat(pageTotal);
			} else {
				PageTempAttr = 'Page ' + currentPageLeft + ' of ' + currentPage + ' // Skip to page';
				PageTempDisplay = currentPageLeft + '-' + currentPage;
			}

			var PageTempInput = $('control-page-number-form-input');
			PageTempInput.writeAttribute({
				title: PageTempAttr
			});
			PageTempInput.value = PageTempDisplay;

			// BUILD ARRAY OF ALL
			if (contentsCreated == "false") { // Does the array exist already?
				var evalThis = ""; // Create array of all pages.
				for (i = 1; i <= parseFloat(pageTotal); i++) {
					evalThis += "contentsListObjects['" + i + "'] = ''; ";
				}

				eval(evalThis);

				// Gives us an array: for every page -> page number where section starts
				var sectionInside = "";

				for (i = 1; i <= parseFloat(pageTotal) + 2; i++) { // Add in the page names for all arrays
					if (contentsListFull[i] != undefined) { // if a contents entry exists for the current number (i)
						sectionInside = i;
						contentsListObjects[i] = sectionInside;
						//alert(contentsListObjects['i']);
					} else if (!contentsListFull[i]) {
						contentsListObjects[i] = sectionInside;
					}
					//alert(contentsListObjects[i] );
				}
				contentsCreated = true; //makes note that contents is created, don't need to iterate over string again.
	
			}
			
			// Get current section name
			currentSection = contentsListFull[contentsListObjects[currentPage]];

			// remove all previous current classes
			$$('#sidebar-contents a').invoke('removeClassName', 'current');

			$('contents' + contentsListObjects[currentPage]).addClassName('current');

			//Set the title of the page appropriately.
			var pageWritten = "";
			if(currentPage == "1") {
				pageWritten = " (Page " + currentPage + ") - "
			} else if(currentPage > pageTotal) {
				pageWritten = " (Page " + (currentPage - 1) + ") - "
			} else {
				pageWritten = " (Page " + (currentPage - 1) + "/" + currentPage + ") - "
			}
			document.title = currentSection + pageWritten + orgName + " Online Interactive " + docName;

		};

		// subscribe to unFocus.History
		unFocus.History.addEventListener('historyChange', this.historyListener);

		// Check for an initial value (deep link).
		// In this demo app, the historyListener can handle the task.
		this.historyListener(unFocus.History.getCurrent());

	},

	//////////////////////////////////
	// add containers for loading bar
	///////////////////////////////////////////////////
	initLoading: function() {
		// adding preload img element to page
		var objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id', 'preloader-image-l');
		$('preload-images').appendChild(objLightboxImage);
		objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id', 'preloader-image-r');
		$('preload-images').appendChild(objLightboxImage);
		// adding loading box element to page
		var objLoading = document.createElement("div");
		objLoading.setAttribute('id', 'loading');
		objLoading.style.display = 'none';
		document.body.appendChild(objLoading);
		// adding loading image element to page
		objLoadingImage = document.createElement("div");
		objLoadingImage.setAttribute('class', "loading-back");
		objLoadingImage.setAttribute('className', "loading-back");
		objLoading.appendChild(objLoadingImage);
		objLoadingImage = document.createElement("img");
		objLoadingImage.setAttribute('src', fileImagesURI + "loading.gif");
		objLoadingImage.setAttribute('alt', 'Loading page request');
		objLoading.appendChild(objLoadingImage);
		var objLoadingText = document.createElement("div");
		objLoadingText.setAttribute('id', "loading-text");
		objLoadingText.innerHTML = "Requesting Pages...";
		objLoading.appendChild(objLoadingText);
		var objLoadingClose = document.createElement("a");
		objLoadingClose.onclick = function() {
			return ReportCast.isLoadingManual();
		};
		objLoadingClose.setAttribute('id', "loading-close");
		objLoadingClose.innerHTML = "x";
		objLoading.appendChild(objLoadingClose);
		var objLoadingRefresh = document.createElement("a");
		objLoadingRefresh.onclick = function() {
			ReportCast.ajaxBookmark('refresh');
			return false;
		};
		objLoadingRefresh.setAttribute('id', "loading-refresh");
		objLoadingRefresh.innerHTML = "R";
		objLoading.appendChild(objLoadingRefresh);

	},

	///////////////////////////////////////////////////
	// Hide Loading Bar Manually
	///////////////////////////////////////////////////
	isLoadingManual: function() {
		Element.hide('loading'); // hide loading bar manually
		return false;
	},

	///////////////////////////////////////////////////
	// PAGE NUMBER FIELD 
	///////////////////////////////////////////////////
	/////Highlight page number box/////
	highlight2: function(obj) {
		obj.activate();
	},

	/////Validate text on entry/////
	form_validate: function() {
		var minval = '1';
		var maxval = parseFloat(pageTotal);
		var objName = $('control-page-number-form-input');
		var numberfield = objName;

		if (ReportCast.chkNumeric(objName, minval, maxval) === false) {
			objName.select();
			objName.focus();
			return false;
		} else {
			return true;
		}
	},

	chkNumeric: function(objName, minval, maxval) {
		var checkOK = "0123456789";
		var checkStr = objName;
		var allValid = true;
		var decPoints = 0;
		var allNum = "";

		for (i = 0; i < checkStr.value.length; i++) {
			ch = checkStr.value.charAt(i);
			for (j = 0; j < checkOK.length; j++) {if (ch == checkOK.charAt(j)) { break; }}
			if (j == checkOK.length) {
				allValid = false;
				break;
			}
			if (ch != ",") {allNum += ch; }
		}
		if (!allValid) {
			//alertsay = "Numbers only please.";
			//alert(alertsay);
			checkStr.value = "1";
			return (false);
		}

		// set the minimum and maximum
		var chkVal = allNum;
		var prsVal = parseInt(allNum, 10);
		if (chkVal !== "" && !(prsVal >= minval && prsVal <= maxval)) {
			//alertsay = "The page number must be between " + minval + " and " + maxval + ".";
			//alert(alertsay);
			checkStr.value = parseFloat(pageTotal);
			return (false);
		}
	},

	///////////////////////////////////////////////////
	// Sidebar Tabs
	///////////////////////////////////////////////////
	loadSidebar: function(tabName, addressPre) {
		//var query = addressPre.split("?");
		var addressp2 = "p=" + currentPage + "&pl=" + currentPageLeft + "&z=" + currentZoom;
		var address = "ajaxCall.php?fcn=" + tabName + ".php&" + addressp2;
		var divID = "sidebar-" + tabName;
		var buttonID = "function-" + tabName;

		//Go through options and set name and ajax location
		var newName = "";
		var notAJAX = false;
		var onLoadDo = ""; // Var to eval after ajax is complete
		switch (tabName) {
		case 'contents':
			newName = "Contents";
			notAJAX = true;
			break;
		case 'search':
			newName = "Search the document";
			onLoadDo = "ReportCast.searchInit()";
			break;
		case 'print':
			newName = "Print a page";
			notAJAX = true;
			ReportCast.printPageDialogue();
			break;
		case 'save':
			newName = "Save a copy";
			break;
		case 'send':
			newName = "Share and Email";
			onLoadDo = "ReportCast.initSend()";
			break;
		case 'help':
			ReportCast.helpOverlay();
			return false; // return from function so that the sidebar isn't changed.
			break;
		}

		// Hide all content blocks
		$('sidebar-contents', 'sidebar-search', 'sidebar-print', 'sidebar-save', 'sidebar-send', 'sidebar-help').invoke('hide').invoke('removeClassName', 'shown');

		//Update name
		$('sidebar-title').update(newName);

		// Stats - notify of sidebar usage
		ReportCast.stats("Sidebar: "+newName);


		//Ajax content across
		if (notAJAX === false) {

			// Create loading element
			var AJAXLoading = $('sidebar-ajaxloading');
			if (AJAXLoading === null) {
				var sidebarAJAXLoading = document.createElement("div");
				sidebarAJAXLoading.setAttribute("id", "sidebar-ajaxloading");
				$('sidebar').appendChild(sidebarAJAXLoading);

				var sidebarAJAXLoadingTemp = document.createElement("div");
				sidebarAJAXLoadingTemp.setAttribute('class', "loading-back");
				sidebarAJAXLoadingTemp.setAttribute('className', "loading-back");
				sidebarAJAXLoading.appendChild(sidebarAJAXLoadingTemp);
				sidebarAJAXLoadingTemp = document.createElement("img");
				sidebarAJAXLoadingTemp.setAttribute('src', fileImagesURI + "loading.gif");
				sidebarAJAXLoadingTemp.setAttribute('alt', 'Loading request');
				sidebarAJAXLoading.appendChild(sidebarAJAXLoadingTemp);
				sidebarAJAXLoadingTemp = document.createElement("div");
				sidebarAJAXLoadingTemp.setAttribute('class', "sidebar-ajaxloading-text");
				sidebarAJAXLoadingTemp.setAttribute('className', "sidebar-ajaxloading-text");
				sidebarAJAXLoadingTemp.innerHTML = "Loading";
				sidebarAJAXLoading.appendChild(sidebarAJAXLoadingTemp);

			}
			
			// Register AJAX Responder
			Ajax.Responders.register({
				onCreate: function() {
					// Show loading
					$('sidebar-ajaxloading').setStyle({
						display: 'block'
					});
				},
				onComplete: function() {
					// Hide loading
					$('sidebar-ajaxloading').setStyle({
						display: 'none'
					});
					if (onLoadDo !== "") {
						eval(onLoadDo);
					}
				}
			});
			// Commence AJAX
			var sidebarAjax = new Ajax.Updater(divID, address);

		}

		//Change state of button
		$('function-contents', 'function-search', 'function-print', 'function-save', 'function-send', 'function-help').invoke('removeClassName', 'current');
		$(buttonID).addClassName('current');

		$('function-over').setAttribute("className", tabName);
		$('function-over').setAttribute("class", tabName);

		//Show clicked block
		$(divID).addClassName('shown').setStyle({
			display: 'block'
		});

		return false;

	},

	///////////////////////////////////////////////////
	// Thumbnails
	///////////////////////////////////////////////////
	loadThumb: function() {
		// check if thumbs div exists. if it does, show the div and return.
		var thumbsVisible = $('overlay');
		if (thumbsVisible !== null) {		
			thumbsVisible.toggleClassName('hidden');
			$('page-area-hide').toggleClassName('hidden');
			return false;
		}

		//var query = addressPre.split("?");
		var addressp2 = "p=" + currentPage + "&pl=" + currentPageLeft + "&z=" + currentZoom;
		var address = "ajaxCall.php?fcn=thumb.php&" + addressp2;
		//var divID = "sidebar-" + tabName;
		//var buttonID = "function-" + tabName;

		// Stats - notify of thumbnails usage
		ReportCast.stats("View Document Thumbnails");

		// Register AJAX Responder
		Ajax.Responders.register({
			onCreate: function() {
				// show loading bar
				Element.show('loading');
			},
			onComplete: function() {
				// Hide loading
				Element.hide('loading');
				//rubbish ie6 handler for recomputing the viewable area
				if(isset(window.isIE6)) {drawPageArea();}
			}
		});
		// Commence AJAX
		var thumbAjax = new Ajax.Updater("page-area", address, {
			insertion: "after"
			});

		return false;

	},

	printPageDialogue: function() {

		var idRight = "print-right";
		var idLeft = "";
		if (currentPageLeft !== "" && currentPageLeft >= "1") {
		} else {
			idRight = "alone";
		}
		if (currentPage !== "" && currentPage <= parseFloat(pageTotal)) {
		} else {
			idLeft = "alone";
		}

		var output = "<p><br /><strong>Please select the page to print:</strong></p>\r" + "<div class='downloads'>";
		if (currentPageLeft !== "" && currentPageLeft >= "1") {
			output += "<a id='"+idLeft+"' onClick=\"return ReportCast.printPage('left');\" ><img src='" + fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + currentPageLeft + "&zoom=print'/>\r<span class='details'>"+currentPageLeft+"</span>\r<span class='details-back'>&nbsp;</span>\r</a>";
		}
		if (currentPage !== "" && currentPage <= parseFloat(pageTotal)) {
			output += "<a id='"+idRight+"' onClick=\"return ReportCast.printPage('right');\" ><img src='" + fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + currentPage + "&zoom=print'/>\r<span class='details'>"+currentPage+"</span>\r<span class='details-back'>&nbsp;</span>\r</a>";
		}
		output += "</div>" + "<p><br /><strong>Tip:</strong><br />For high quality printing or to print multiple pages, please <a href='" + fileIncludeURI + "functions/save.php?org=" + orgPrefix + "&doc=" + docPrefix + "&pl=" + (currentPage - 1) + "&p=" + currentPage + "' target='_blank' onClick='return ReportCast.loadSidebar(\"save\", \"" + fileIncludeURI + "functions/save.php?org=" + orgPrefix + "&doc=" + docPrefix + "&pl=" + currentPageLeft + "&p=" + currentPage + "\");'>download the PDF of the page you want to print</a> and print from your PDF reader.</p>";

		$('sidebar-print').innerHTML = output;

	},

	///////////////////////////////////////////////////
	// Create and show print page 
	///////////////////////////////////////////////////
	printPage: function(pageLR) {

		//get URL of image to be printed
		if (pageLR == "left") {
			printImageURL = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + currentPageLeft + "&zoom=3";
		} else {
			printImageURL = fileIncludeURI + "page.php?orgPrefix=watc&" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + currentPage + "&zoom=3";
		}

		if (! $('print-image')) {
			// adding image container
			var printImageDiv = document.createElement("div");
			printImageDiv.setAttribute('id', 'print-image-div');
			document.body.appendChild(printImageDiv);
			var printImageContainer = document.createElement("img");
			printImageContainer.setAttribute('id', 'print-image');
			printImageContainer.setAttribute('src', '');
			$('print-image-div').appendChild(printImageContainer);
			var printImageTempContainer = document.createElement("img");
			printImageTempContainer.setAttribute('id', 'print-image-temp');
			printImageTempContainer.setAttribute('height', '1');
			printImageTempContainer.setAttribute('width', '1');
			printImageTempContainer.setAttribute('src', '');
			$('preload-images').appendChild(printImageTempContainer);

			var printLoadingContainer = document.createElement("div");
			printLoadingContainer.setAttribute('id', 'print-loading');
			$('sidebar-print').appendChild(printLoadingContainer);
			var printLoadingTemp = document.createElement("div");
			printLoadingTemp.setAttribute('class', "loading-back");
			printLoadingTemp.setAttribute('className', "loading-back");
			printLoadingContainer.appendChild(printLoadingTemp);
			printLoadingTemp = document.createElement("img");
			printLoadingTemp.setAttribute('src', fileImagesURI + "loading.gif");
			printLoadingTemp.setAttribute('alt', 'Loading request');
			printLoadingContainer.appendChild(printLoadingTemp);
			printLoadingTemp = document.createElement("div");
			printLoadingTemp.setAttribute('class', "print-loading-text");
			printLoadingTemp.setAttribute('className', "print-loading-text");
			printLoadingTemp.innerHTML = "Loading full size image for printing";
			printLoadingContainer.appendChild(printLoadingTemp);
		}

		//Show loading message
		$("print-loading").style.display = 'block'; // show print loading message
		isPrinting = true;

		//Get Image
		var imgContainer = $('print-image');
		//Swap Image
		var printImageTemp = new Image();
		printImageTemp.onload = function() {
			$('print-image-temp').src = printImageURL;
			var printImage = document.createElement('img');
			printImage.onload = function(evt) {
				imgContainer.src = this.src;
				$('print-loading').style.display = "none"; // hide loading bar once image is preloaded
				window.print();
			};
			printImage.src = printImageURL;
			printImageTemp.onload = function() {}; //	clear onLoad, IE behaves irratically with animated gifs otherwise 
		};
		printImageTemp.src = printImageURL;
		return false;
	},

	///////////////////////////////////////////////////
	// Make Help Overlay appear 
	///////////////////////////////////////////////////
	helpOverlay: function(state) {

		//turn on or off?
		if (state != "off") {
			state = "on";
		}

		if (! $('help-overlay')) {
			// Create Containing Div
			var helpDiv = document.createElement("div");
			helpDiv.setAttribute('id', 'help-overlay');
			document.body.appendChild(helpDiv);

			// Create link and add ID and onclick
			var helpLink = document.createElement("a");
			helpLink.onclick = function() {
				return ReportCast.helpOverlay('off');
			};
			helpDiv.appendChild(helpLink);

			// Create background
			var helpBack = document.createElement("div");
			helpBack.setAttribute('id', 'help-overlay-back');
			helpDiv.appendChild(helpBack);
			
			return false;		// on first load the function terminates here
		}
		
		// When it's not the first load, control the link by toggling the hide class.
		$('help-overlay').toggleClassName('hide');


	},

	///////////////////////////////////////////////////
	// SHOW CONTENTS SIDEBAR WHEN PAGE IS CHANGED WHILE PRINT, SAVE OR SEND SIDEBARS ARE OPEN. STOPS OLD CONTENT FROM BEING SHOWN. 
	///////////////////////////////////////////////////
	closeSidebars: function() {
		var tempPrint = $('sidebar-print').hasClassName('shown');
		var tempSave = $('sidebar-save').hasClassName('shown');
		var tempSend = $('sidebar-send').hasClassName('shown');

		if (tempPrint === true || tempSave === true || tempSend === true) {
			ReportCast.loadSidebar('contents');
		}

	},

	///////////////////////////////////////////////////
	// ADD CLOSE LINKS TO SIDEBAR MODULES 
	///////////////////////////////////////////////////
	sideAddClose: function() {
		// Get elements to append to
		var parentDT = $('rhs-bottom').getElementsByTagName('dt');
		parentDT = $A(parentDT);

		parentDT.each(function(s) {
			// Create link to toggle appearance
			var sideAddTemp = document.createElement("a");
			sideAddTemp.setAttribute('class', 'sidebar-close-toggle');
			sideAddTemp.setAttribute('className', 'sidebar-close-toggle');
			sideAddTemp.onclick = function() {
				return ReportCast.sideMinimise(this);
			};
			sideAddTemp.setAttribute('title', 'Hide content of this section');
			// Append link to container
			$(s).appendChild(sideAddTemp);
		});
	},

	///////////////////////////////////////////////////
	// MINIMISE SIDEBAR MODULES 
	///////////////////////////////////////////////////
	sideMinimise: function(elmID) {
		if(isWorking === "true") {return false;} else {isWorking="true";setTimeout(function(){isWorking="false";}, 550);} //disables button for specified time
		
		// Find the module parent element
		var linksObject = $(elmID);
		linksObject = linksObject.parentNode.parentNode;

		var elemHeight = $(linksObject).getHeight();
		var sibebarBottom = $('sidebar').getStyle('bottom');

		var hasClassTemp = linksObject.hasClassName('closed');

		if (hasClassTemp === true) { //open it
			linksObject.toggleClassName('closed');

			var calc = parseFloat(sibebarBottom) + 90 - 22;
			$('sidebar').morph({ bottom: calc + 'px'}, { duration: 0.5 });
			$(linksObject).morph({ height: '90px'}, { duration: 0.5 });

		} else if (hasClassTemp === false) { //close it
			linksObject.toggleClassName('closed');
			calc = (parseFloat(sibebarBottom) - parseFloat(elemHeight)) + 22;
			$('sidebar').morph({ bottom: calc + 'px'}, { duration: 0.5 });
			$(linksObject).morph({ height: '22px'}, { duration: 0.5 });
		}

	// if IE6
	if(isset(window.isIE6)) {setTimeout(drawPageArea, 550);} // adds .05 of a second wait so that the effects have time to run before calling the resize.

		return false;

	},

	///////////////////////////////////////////////////
	///////// SEND PAGE 
	///////////////////////////////////////////////////
	initSend: function() {

		var headID = document.getElementsByTagName("head")[0];
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = fileIncludeURI + 'functions/wysihat.js';
		headID.appendChild(newScript);

		/* //Has to be reencoded with &lt;, &gt; etc for Safari.
		var jsMessage = "<p>Hi,<\/p>\n\n" +
						"<p>Please find attached a link to the <?php echo("$orgName $docName") ?>. Click on the link below to view the interactive document right in your browser window.<\/p>\n\n" +
						"<p><a href='<?php echo("$fileOrgRootURI$docPrefix/?p=$currentPage&z=$currentZoom") ?>' ><?php echo("$orgName Interactive $docName") ?><\/a><\/p>\n\n" +
						"<p>Regards.<\/p>\n\n"; 	*/

		var jsMessage = "&lt;p&gt;Hello,&lt;\/p&gt;"+
						"&lt;p&gt;Please find attached a link to the " + orgName + " " + docName + ". Click on the link below to view the interactive document right in your browser window.&lt;\/p&gt;"+
						"&lt;p&gt;&lt;a href=&#34;" + fileOrgRootURI + docPrefix + "\/?p=" + currentPage + "&z=" + currentZoom + "&#34; &gt;" + orgName + " Interactive " + docName + "&lt;\/a&gt;&lt;\/p&gt;"+
						"&lt;p&gt;Regards.&lt;\/p&gt;";
		$('message').innerHTML = jsMessage;

		$('show-all-a').setStyle({
			display: 'block'
		});
		$('show-all-div').addClassName('hidden');
		$('email').activate();
	},

	removeInputText: function(elem) {
		if (elem.value == 'friend@friendsemail.com' || elem.value == 'me@myemail.com') {
			elem.value = '';
		//	elem.value = null;
		}
		return false;
	},

	validateSend: function(f) {
		var validate_temp = document.getElementById('emailfrom');
		var email_r = validate_temp.value;
		validate_temp = document.getElementById('email');
		var email_s = validate_temp.value;
		validate_temp = document.getElementById('subject');
		var subject = validate_temp.value;
		validate_temp = document.getElementById('message');
		var message = validate_temp.value;

		//Check that the fields are not still the defaults
		if (email_r == "me@myemail.com" || email_s == "friend@friendsemail.com") {
			if (! $('confirm')) {
				var confirmTemp = document.createElement("div");
				confirmTemp.setAttribute('id', 'confirm');
				$('send').insert({
					before: confirmTemp
				});
			}

			$('confirm').update("<span>Please enter an email into the 'To' and 'From' fields.</span>");
			$('confirm').highlight({ startcolor: '#ffd0d0', endcolor: '#f0f0f0'});


			if (email_s == "friend@friendsemail.com") {
				document.getElementById('email').focus();
			} else if (email_r == "me@myemail.com") {
				document.getElementById('emailfrom').focus();
			}

			return (false);
		}

		// Check that no fields are blank
		if (email_r === "" || email_s === "" || subject === "" || message === "") {
			if (! $('confirm')) {
				confirmTemp = document.createElement("div");
				confirmTemp.setAttribute('id', 'confirm');
				$('send').insert({
					before: confirmTemp
				});
			}

			$('confirm').update("<span>All fields are required.</span>");
			$('confirm').highlight({ startcolor: '#ffd0d0', endcolor: '#f0f0f0'});

			if (email_s === "") {
				document.getElementById('email').focus();
			} else if (email_r === "") {
				document.getElementById('emailfrom').focus();
			}

			return (false);
		}

		// check the first email address 
		if (!ReportCast.check_email(email_r)) {
			if (! $('confirm')) {
				confirmTemp = document.createElement("div");
				confirmTemp.setAttribute('id', 'confirm');
				$('send').insert({
					before: confirmTemp
				});
			}

			$('confirm').update("<span>Please check your email address.</span>");
			$('confirm').highlight({ startcolor: '#ffd0d0', endcolor: '#f0f0f0'});

			document.getElementById('emailfrom').focus();
			//			// if the browser is Netscape 6 or IE
			//			if(document.all || document.getElementByID)
			//			{
			//			}
			return false;
		}

		// check the second email address
		if (!ReportCast.check_email(email_s)) {
			if (! $('confirm')) {
				confirmTemp = document.createElement("div");
				confirmTemp.setAttribute('id', 'confirm');
				$('send').insert({
					before: confirmTemp
				});
			}

			$('confirm').update("<span>Please check the recipient email address.</span>");
			$('confirm').highlight({ startcolor: '#ffd0d0', endcolor: '#f0f0f0'});

			document.getElementById('email').focus();
			//			if(document.all || document.getElementByID)
			//			{
			//			}
			return false;
		}

		$('send-form').request({
			onComplete: function(transport) {
				$('sidebar-send').update(transport.responseText);
			}
		});
		return false;
	},

	check_email: function(e) {
		ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

		for (i = 0; i < e.length; i++) {
			if (ok.indexOf(e.charAt(i)) < 0) {
				return (false);
			}
		}

		if (document.images) {
			re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
			re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
			if (!e.match(re) && e.match(re_two)) {
				return ( - 1);
			}
		}
	},

	showAllDiv: function() {

		widgInit();

		$('show-all-div').toggleClassName('hidden');
		$('show-all-a').setStyle({
			display: 'none'
		});

		return false;
	},

	///////////////////////////////////////////////////
	///////// Search
	///////////////////////////////////////////////////
	searchInit: function() {
		$('search-input').activate();
		return false;
	},

	searchForm: function() {

		if ($('search-input').value == "Enter keyword to search") { // if no search term entered.
			if (! $('search-confirm')) {
				var confirmTemp = document.createElement("div");
				confirmTemp.setAttribute('id', 'search-confirm');
				$('search-submit').insert({
					before: confirmTemp
				});
			}

			$('search-confirm').update("<span>Please enter a keyword to search.</span>");
			$('search-confirm').highlight({ startcolor: '#ffd0d0', endcolor: '#f0f0f0'});
			$('search-input').activate();
			return false;
		}

		$('search-form').request({
			onComplete: function(transport) {
				$('sidebar-search').update(transport.responseText);
				if ($('search-confirm')) {
					$('search-confirm').highlight({ startcolor: '#ffd0d0', endcolor: '#f0f0f0'});
				}
			}
		});
		return false;
	},

	searchLink: function(link) {
		(new Ajax.Updater($('sidebar-search'), link.href));
		$('sidebar-search').scrollTop = 0;

		if ($('search-confirm')) {
			$('search-confirm').highlight({ startcolor: '#ffd0d0', endcolor: '#f0f0f0'});
		}

		return false;
	},

	
	/////////////////////////////////////
	// STATS BITS.
	/////////////////////////////////////
	stats: function(action) {
		if(statsSiteID !== ""){	
			piwik_url = statsURI+"piwik.php";

			if (! $('stats')) {Piwik.log(action, statsSiteID, piwik_url); return true;}

			var NewImage = Piwik._getUrlLog(action, statsSiteID, piwik_url);

			//Get Image
			var imgContainer = $('stats');

			var StatImageTemp = new Image();
				StatImageTemp.onload=function(){
					$('stats-pre').src = NewImage;
					var TheImage = document.createElement('img');
						imgContainer.src=this.src;
					TheImage.src = NewImage;
					StatImageTemp.onload=function(){};	//	clear onLoad, IE behaves irratically with animated gifs otherwise 
				};
			StatImageTemp.src = NewImage;
		} //end no stats
		return true;
	},
	
	onLoadJS: function() {
		// NAVIGATION buttons
		$('control-page-prev').onclick = function() { 
			return ReportCast.pagePrev(); }
		$('control-page-number-form-input').onclick = function() { 
			return ReportCast.highlight2(this);}
		$('control-page-number-form-input').onkeyup = function() { 
			return ReportCast.form_validate();}
		$('control-page-next').onclick = function() { 
			startupTooltip('off'); return ReportCast.pageNext();}
		$('control-zoom-in').onclick = function() { 
			return ReportCast.zoomInNew();}
		$('control-zoom-out').onclick = function() { 
			return ReportCast.zoomOutNew();}
		$('control-zoom-level-3').onclick = function() { 
			return ReportCast.zoomSpecific(3); return false;}
		$('control-zoom-level-2').onclick = function() { 
			return ReportCast.zoomSpecific(2); return false;}
		$('control-zoom-level-1').onclick = function() { 
			return ReportCast.zoomSpecific(1); return false;}
		$('control-view-full').onclick = function() { 
			return ReportCast.fullScreen();}
		$('control-view-thumb').onclick = function() { 
			return ReportCast.loadThumb();}



		// FUNCTION buttons
		$('function-contents').onclick = function() { 
			return ReportCast.loadSidebar('contents', this.href); }

		$('function-search').onclick = function() { 
			return ReportCast.loadSidebar("search", this.href); }

		$('function-print').onclick = function() { 
			return ReportCast.loadSidebar("print", this.href); }

		$('function-save').onclick = function() { 
			return ReportCast.loadSidebar("save", this.href); }

		$('function-send').onclick = function() { 
			return ReportCast.loadSidebar("send", this.href); }

		$('function-help').onclick = function() { 
			return ReportCast.loadSidebar("help", this.href); }

	}
};

///////////////////////////////////////////////////
///////// ACTIVATE ON PAGE LOAD 
///////////////////////////////////////////////////
document.observe("dom:loaded",
function() {
	$('page-text').remove(); //Remove text version of pages.
	$('control-view-full').removeClassName('na'); //Enables button for JS users
	
	//Adds JS-only parts
	ReportCast.sideAddClose(); 
	ReportCast.onLoadJS();

	// if IE6
	if(isset(window.isIE6)) {
		drawPageArea();
		try {document.execCommand("BackgroundImageCache", false, true);} catch(e){}; // forces ie6 to cache css background images
	}
	
	DragScrollable.prototype.initialize('page-area');
	var ReportCastApp = new ReportCast.ajaxHistory();

	//initialise tooltips
	$$("a").each( function(link) {
		new Tooltip(link);
	});
	$$("input").each( function(link) {
		new Tooltip(link);
	});
	
	// remove alt attributes from images
	$("page-image-l").writeAttribute("alt", "");
	$("page-image-r").writeAttribute("alt", "");

	document.stopObserving("dom:loaded");
});

///////////////////////////////////////////////////
///////// ACTIVATE ON FULL PAGE LOAD 
///////////////////////////////////////////////////
window.onload = function() {
	if(isset(window.isIE6)) {
		if(isset($('load-overall'))) {
			setTimeout(function() {$('load-overall').hide();}, 2000);
		}
	} else {
		$('load-overall').hide(); //Hides loading window 
	}
	
	//Initialise onload help
	startupTooltip("on");
	setTimeout("startupTooltip('off')",10000);

	//Postload the next images once the initial page load has occured.
	ReportCast.postload();


};

///////////////////////////////////////////////////
///////// TOOLTIP STUFF 
///////////////////////////////////////////////////
// Tooltips Class
// A superclass to work with simple CSS selectors
var Tooltips = Class.create();
Tooltips.prototype = {
	initialize: function(selector, options) {
		var tooltips = $$(selector);
		tooltips.each( function(tooltip) {
			new Tooltip(tooltip, options);
		});
	}
};
// Tooltip Class
var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(el, options) {
		this.el = $(el);
		
		if(!this.el.title) return; // from http://code.google.com/p/tooltips/issues/detail?id=10 --> don't show tooltip if title is empty.

		this.initialized = false;
		this.setOptions(options);
		
		// Event handlers
		this.showEvent = this.show.bindAsEventListener(this);
		this.hideEvent = this.hide.bindAsEventListener(this);
		this.updateEvent = this.update.bindAsEventListener(this);
		Event.observe(this.el, "mouseover", this.showEvent );
		Event.observe(this.el, "mouseout", this.hideEvent );
		
		// Removing title from DOM element to avoid showing it
		this.content = this.el.title.stripScripts().strip();
		this.el.title = "";

		// If descendant elements has 'alt' attribute defined, clear it
		if (this.el.descendants()) { // required for input boxes.
			this.el.descendants().each(function(el){
				if(Element.readAttribute(el, 'alt'))
					el.alt = "";
			});
		}
	},
	setOptions: function(options) {
		this.options = {
			backgroundColor: '#000', // Default background color
			borderColor: '#000', // Default border color
			textColor: '#fff', // Default text color (use CSS value)
			textShadowColor: '', // Default text shadow color (use CSS value)
			maxWidth: 250,	// Default tooltip width
			align: "left", // Default align
			delay: 500, // Default delay before tooltip appears in ms
			mouseFollow: false, // Tooltips follows the mouse moving
			opacity: 0.6, // Default tooltips opacity
			appearDuration:.1, // Default appear duration in sec
			hideDuration: .1 // Default disappear duration in sec
		};
		Object.extend(this.options, options || {});
	},
	show: function(e) {
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		if(!this.initialized)
			this.timeout = window.setTimeout(this.appear.bind(this), this.options.delay);
	},
	hide: function(e) {
		if(this.initialized) {
			this.appearingFX.cancel();
			if(this.options.mouseFollow)
				Event.stopObserving(this.el, "mousemove", this.updateEvent);
			new Effect.Fade(this.tooltip, {duration: this.options.hideDuration, afterFinish: function() { Element.remove(this.tooltip) }.bind(this) });
		}
		this._clearTimeout(this.timeout);
		
		this.initialized = false;
	},
	update: function(e){
		this.xCord = Event.pointerX(e);
		this.yCord = Event.pointerY(e);
		this.setup();
	},
	appear: function() {
		// Building tooltip container
		this.tooltip = new Element("div", { className: "tooltip", id: "tooltip", style: "display: none" });
		
		var content = new Element("div", { className: "xboxcontent", id: "xboxcontent", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + 
			((this.options.textColor != '') ? "; color:" + this.options.textColor : "") + 
			((this.options.textShadowColor != '') ? "; text-shadow:2px 2px 0" + this.options.textShadowColor + ";" : "") }).update(this.content);
			
		// Building and injecting tooltip into DOM
		this.tooltip.insert(content);//insert(arrow).insert(top).insert(content).insert(bottom);
		$(document.body).insert({'top':this.tooltip});
		
		// Coloring arrow element
		this.tooltip.select('.xarrow b').each(function(el){
			if(!el.hasClassName('a1'))
				el.setStyle({backgroundColor: this.options.backgroundColor, borderColor: this.options.borderColor });
			else
				el.setStyle({backgroundColor: this.options.borderColor });
		}.bind(this));
		
		Element.extend(this.tooltip); // IE needs element to be manually extended
		this.options.width = this.tooltip.getWidth() + 1; // Quick fix for Firefox 3
		this.tooltip.style.width = this.options.width + 'px'; // IE7 needs width to be defined
		
		this.setup();
		
		if(this.options.mouseFollow)
			Event.observe(this.el, "mousemove", this.updateEvent);
			
		this.initialized = true;
		this.appearingFX = new Effect.Appear(this.tooltip, {duration: this.options.appearDuration, to: this.options.opacity });
	},
	setup: function(){
		// If content width is more then allowed max width, set width to max
		if(this.options.width > this.options.maxWidth) {
			this.options.width = this.options.maxWidth;
			this.tooltip.style.width = this.options.width + 'px';
		}
			
		// Tooltip doesn't fit the current document dimensions
		if(this.xCord + this.options.width >= Element.getWidth(document.body)) {
			this.options.align = "right";
			this.xCord = this.xCord - this.options.width + 20;
//			this.tooltip.down('.xarrow').setStyle({left: this.options.width - 24 + 'px'});
		} else {
			this.options.align = "left";
//			this.tooltip.down('.xarrow').setStyle({left: 12 + 'px'});
		}

		this.tooltip.style.left = this.xCord - 7 + "px";

		// Tooltip appears below bottom of window, fix it!
		if(this.yCord + 50 >= document.viewport.getHeight()) {
			this.tooltip.style.top = document.viewport.getHeight() - 43 + "px";
			this.tooltip.style.left = this.xCord - 30 + "px";
		} else {
			this.tooltip.style.top = this.yCord + 12 + "px";
		}
		
	},
	_clearTimeout: function(timer) {
		clearTimeout(timer);
		clearInterval(timer);
		return null;
	}
};


function startupTooltip(Sevent) {
	var Sevent;
	if (Sevent == "on") {
		var startupMessage = "Startup Message";
		var startupHTML = "<div id='startupTooltip' class='tooltip below' style='display:none; width: 165px; right: 310px; top: 85px; opacity: 0.6; -moz-opacity: 0.6; -khtml-opacity: 0.6; -webkit-opacity: 0.6; filter: progid:DXImageTransform.Microsoft.Alpha(opacity=60);'><div class='xboxcontent' style='border:none; background-color:#000; color:#fff; padding:1.2em;'>Click Here to Continue Reading</div><a id='loading-close' onclick=\"return startupTooltip('off');\">x</a><div class='bubble-arrow'></div></div>";
		$(document.body).insert({'top':startupHTML});
		$('startupTooltip').appear({ duration: 0.5, to: 0.6 });
	} else if (Sevent == "off" && !($("startupTooltip").hasClassName('off'))) {
		$('startupTooltip').fade({ duration: 0.5, to: 0 });
		$("startupTooltip").addClassName("off");
	}
	return false;
}
