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

//inset 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";
	} else if (fullScreen != "fullscreen") {
		iePageArea = $("page-area");
		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
		// create object
		var imageObj = new Image();

		var pageUrlLeft_next = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + (parseFloat(page_new_left) + 2) + "&zoom=" + currentZoomNew;
		var pageUrlRight_next = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + (parseFloat(page_new_right) + 2) + "&zoom=" + currentZoomNew;
		var pageUrlLeft_zoomin = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + page_new_left + "&zoom=" + (parseFloat(currentZoomNew) + 1);
		var pageUrlRight_zoomin = fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + page_new_right + "&zoom=" + (parseFloat(currentZoomNew) + 1);
		// set image list
		var images = new Array();
		images[0] = pageUrlLeft_next;
		images[1] = pageUrlRight_next;
		images[2] = pageUrlLeft_zoomin;
		images[3] = pageUrlRight_zoomin;

		// start preloading
		var i = 0;
		for (i = 0; i <= images.length; i++) {
			imageObj.src = images[i];
		}
	},
	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: Math.round(page_scale / 100 * (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: Math.round(page_scale / 100 * (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);
	},

	///////////////////////////////////////////////////
	// Full Screen 
	///////////////////////////////////////////////////
	fullScreen: function() {
		if(isWorking == "true") {return false;} else {isWorking="true";setTimeout(function(){isWorking="false";}, 850);} //disables button for specified time
	
		$('page-area').morph({ right: '0px', top: '0px'}, { duration: 0.8 });
		$('controls').morph({ top: '-23px', right: '-1px', 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');

		//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 });
		$('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');

		//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;

		//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;

			////////////////////////////////////////////////////////
			// Page sizes
			// Get current page dimensions
			page_width_current = imageWidth * currentZoomScale;
			page_height_current = imageHeight * currentZoomScale;

			// Get new page dimensions
			page_width_new = imageWidth * currentZoomNewScale;
			page_height_new = imageHeight * currentZoomNewScale;
			
			page_width_new = Math.round(page_width_new);
			page_height_new = Math.round(page_height_new);
			
			
			////////////////////////////////////////////////////////
			// 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.
			}

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

			$('contents' + contentsListObjects[currentPage]).addClassName('current');
			
			//Set the title of the page appropriately.
			document.title = "NEW TITLE";//currentSection + " - " + orgName + " Online Interactive " + docName;
			//alert(document.title);

		};

		// 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;

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

		//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 = "Send to Colleague";
			onLoadDo = "ReportCast.initSend()";
			break;
		case 'help':
			newName = "ReportCast Help";
			break;
		}

		//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;

	},

	printPageDialogue: function() {
		var output = "<p><br /><strong>Please select the page to print:</strong></p>" + "<div>";
		if (currentPageLeft !== "" && currentPageLeft >= "1") {
			output += "<a onClick=\"return ReportCast.printPage('left');\" ><img src='" + fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + currentPageLeft + "&zoom=print' id='print-preview-l' /></a>";
		}
		if (currentPage !== "" && currentPage <= parseFloat(pageTotal)) {
			output += "<a onClick=\"return ReportCast.printPage('right');\" ><img src='" + fileIncludeURI + "page.php?orgPrefix=" + orgPrefix + "&docPrefix=" + docPrefix + "&page=" + currentPage + "&zoom=print' id='print-preview-r' /></a>";
		}
		output += "</div>" + "<p><br /><strong>Tip:</strong><br />For high quality printing, please <a 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;

	},

	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;
	},

	///////////////////////////////////////////////////
	// 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/widgEditor.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='" + fileOrgRootURI + docPrefix + "\/?p=" + currentPage + "&z=" + currentZoom + "' &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;
	},

	///////////////////////////////////////////////////
	///////// JS loading element for ReportCast
	///////////////////////////////////////////////////
	overallLoad: function() {

		//		var currentURI = window.location.protocol+"//"+window.location.host+window.location.pathname;
		var newURI = window.location.protocol + "//" + window.location.host + window.location.pathname + "?p=" + currentPage + "&z=" + currentZoom + "&ui=nojs";

		var overallLoadDivTemp = document.createElement("div");
		overallLoadDivTemp.setAttribute("id", "load-overall");
		$('preload-images').insert({
			before: overallLoadDivTemp
		});

		var overallLoadTemp = document.createElement("div");
		overallLoadTemp.setAttribute('class', "loading-back");
		overallLoadTemp.setAttribute('className', "loading-back");
		overallLoadDivTemp.appendChild(overallLoadTemp);
		overallLoadTemp = document.createElement("img");
		overallLoadTemp.setAttribute('src', fileImagesURI + "loading.gif");
		overallLoadTemp.setAttribute('alt', 'Loading ReportCast Document');
		overallLoadDivTemp.appendChild(overallLoadTemp);
		overallLoadTemp = document.createElement("span");
		overallLoadTemp.setAttribute('class', "load-overall-first");
		overallLoadTemp.setAttribute('className', "load-overall-first");
		overallLoadTemp.innerHTML = "Loading " + docName;
		overallLoadDivTemp.appendChild(overallLoadTemp);
		overallLoadTemp = document.createElement("span");
		overallLoadTemp.setAttribute('class', "load-overall-next");
		overallLoadTemp.setAttribute('className', "load-overall-next");
		overallLoadTemp.innerHTML = "<a href='" + newURI + "'>Load basic HTML version</a> (for slow connections)";
		overallLoadDivTemp.appendChild(overallLoadTemp);

	},
	
	
	/////////////////////////////////////
	// STATS BITS.
	/////////////////////////////////////
	stats: function(action) {
		if(statsSiteID !== ""){	
			piwik_url = "http://stats.reportcast.com.au/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;
	}
};

///////////////////////////////////////////////////
///////// ACTIVATE ON PAGE LOAD 
///////////////////////////////////////////////////
document.observe("dom:loaded",
function() {
	$('jsRemoveMe').remove(); //Remove text version of pages.
	$('page-text').remove(); //Remove text version of pages.
	$('control-view-full').removeClassName('na'); //Enables button for JS users
	ReportCast.overallLoad(); // creates loading box for ReportCast.
	ReportCast.sideAddClose(); //Adds minimise toggle to modules
	
	// if IE6
	if(isset(window.isIE6)) {drawPageArea();}
	
	DragScrollable.prototype.initialize('page-area');
	var ReportCastApp = new ReportCast.ajaxHistory();


	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 
	}
		
};



