// Main javascript file for brianmacmillan.com
// Copyright 2008-2010 by Brian MacMillan
// Notes on variable prefixes:
// ai - array integer
// pi - parameter integer eg function myfunct(piWhichValue){}
//  i - locally scoped integer, eg var iAmount = 1;
//  f - locally scoped float, eg var fAmount = 1.9;
//  e - element, eg e = document.getElementById("toc1");
//  s - locally scoped string.
//NBNB Several of the functions below are not used any more

//NB Brian flip the LOCALHOST flag to false before deployment.
var LOCALHOST = true;
var SUCCESS = 0;  // queries return 0 on success, non zero on failiure.

// NB Used  by navArrowOnMouseOver. To scope locally in an interface class
var ARROW_NEXT ="pictures/arrow-next-light-orange.png"; 
var ARROW_PREVIOUS="pictures/arrow-previous-light-orange.png";
var ARROW_NEXT_MOUSE_OVER ="pictures/arrow-next-orange.png";
var ARROW_PREVIOUS_MOUSE_OVER="pictures/arrow-previous-orange.png";
	

var TOC_NAVBAR_GUTTER = 0; //space (percent), between navbar images


var httpRequest;  // ajax object. dupe with jQuery.
if (window.XMLHttpRequest)
{
	httpRequest = new XMLHttpRequest();
} else
{
	httpRequest =  new ActiveXObject("Microsoft.XMLHTTP");
}

/********** end of global variable definitions ***********/

//NB To delete? Use this only for IE6 and below. Does this code work?
//var giFirstLineAdjustmentIE = 27; // exception for IE. First para client height is off by 27 px.
//giFirstLineAdjustmentIE = 26; //shouldn't be necessary with jQuery.

/*********************************/
/* *** DOCUMENT READY *** */
/*********************************/
documentReadyStories = function(){
	document.getElementById('no-javascript').style.display="none";

	if(window.getComputedStyle) 
	{
		window.onresize = function(event) {windowResize(event)};
		window.onkeyup = function(event) {windowKeyUp(event);}
	} else
	{
		//ie
		document.onresize = windowResize;
		document.onkeyup = windowKeyUp;	
	}
	logEvent(0);
	//drawPage("load");
	setEventHandlers();
	//try this to trap for keyUp events - document.onkeyup=windowKeyUp(event); 
	//dock2 for bottom dock for top of screen //
	$('#icon-dock').Fisheye(
	{
		maxWidth: 40,
		items: 'a',
		itemsText: 'span',
		container: '#icon-dock-inner',
		itemWidth: 25,
		proximity: 20,
		alignment : 'left',
		valign: 'top',
		halign : 'center',
	});

	$('#icon-dock2').Fisheye(
	{
		maxWidth: 40,
		items: 'a',
		itemsText: 'span',
		container: '#icon-dock2-inner',
		itemWidth: 25,
		proximity: 20,
		alignment : 'left',
		valign: 'top',
		halign : 'center',
	});
	//initialize jquery.itooltip.js
	$('.toc-nav-icon').ToolTip(
	{
		className : 'tocToolTip',
		position: 'bottom',
		delay: 0
	});
	$('.blind-mennu').ToolTip(
	{
		className : 'blindMenuToolTip',
		position: 'bottom',
		delay: 100
	});

	//SLIDE SHOW - MIXTURE OF GALLERIA AND SERIALSLIDE AND SLIDETO plugins
	$('.gallery').addClass('gallery-items'); // adds new class name to maintain degradability
	$('ul.gallery-items').colflow({
		history   : true, // activates the history object for bookmarking, back-button etc.
		clickNext : true, // helper for making the image clickable
		insert    : '#main-image', // the containing selector for our main image
		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes

			// fade in the image & caption
			image.css('display','none').fadeTo(200,50);
			//image.fadeOut(1000);
			image.fadeIn(200);

			//caption.css('display','none').fadeIn(0);

			// fetch the thumbnail container
			var _li = thumb.parents('li');

			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(0,0.3);

			// fade in active thumbnail
			thumb.fadeTo('fast',1).addClass('selected');

			// add a title for the clickable image
			image.attr('title','Click for next image. Shift-click for previous image.');
		},
		onThumb : function(thumb) { // thumbnail effects goes here

			// fetch the thumbnail container
			var _li = thumb.parents('li');

			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';

			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(500);

			// hover effects
			thumb.hover(
				function() { thumb.fadeTo('fast',1); },
				function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
			)
		}
	});

	setTimeout('$.colflow.drawPage("resize")',1000);	

	/* Drag and drop stuff not activated */
	/*
	$(".dragable").draggable({helper: 'clone'});
	$(".dropable").droppable(
	{
	accept: ".dragable",
	activeClass: 'dropable-active',
	hoverClass: 'dropable-hover',
	drop: function(ev, ui) 
		{
			$(this).append("");
			var draggable = $.ui.ddmanager.current;
			try 
			{
				alert("Would you like to add " +draggable.helper[0].innerHTML + "to your shopping cart?");
			} catch(e)
			{
				alert("error in drop " +e.message);
			}
			//var d = document.getElementById('content-inner');
		}
	});
	*/
}
/* *** End jQuery Document Ready **** */
setEventHandlers=function(){
	$(".img-next").click(function() {$.colflow.next()});
	$(".img-previous").click(function() {$.colflow.previous()});

	$(".dock-item").click(function() {iconDockEventHandler(this)});
	$(".dock-item2").click(function() {iconDockEventHandler(this)});
	$(".toc-nav-icon").mouseover(function() {tocNavMouseOver(this)});
	$(".toc-nav-icon").mouseout(function() {tocNavMouseOut(this)});
	$(".toc-nav").mouseup(function() {navShowChapter(this)});
	headerNavigationEventHandler();

	//loaded allows events to be active before the page is loaded.
	//firing it here, after the document load event achieves nothing.
	//i moved it here because the overhead of the code actually slowed down load time
	// which is a bigger priority for me. in summary this code is transitional
	//may selectively move functions to before document ready


	loaded('content',contentEventHandler);
	loaded('content-inner',contentInnerEventHandler);
	loaded('content-header-left-right',contentHeaderLeftEventHandler);
	loaded('content-header-right-left',contentHeaderRightEventHandler);
	helpEventHandler();
	loaded("comments",$.bm_comments.commentsEventHandler);
	loaded('login',$.bm_login.loginEventHandler);

	//loaded("help",helpEventHandler);
//	loaded_two('preferences-personal-section',preferencesEventHandler,0);

//	loaded('tab-wide-narrow-img',tabWideNarrowEventHandler);

//	loaded("rating-title",titleEventHandler);

//	loaded("tab",tabEventHandler);

	//document.getElementById("content-images").style.zIndex="1";//.style.display="none";
	//document.getElementById("navbar-photo").style.display="none";
	
	//Initialize colflow plugin
	/*
	$("#content-text").colflow({
		storyid : 0,
		chapterid : 0,
		// g(s)(i)BaseFontSize - dynamically determined; initially from style sheet in setGlobals
		basefontsizestring : "12px", //px 
		// $.colflow.fontsize is integer version of $.colflow.basefontsizestring. For convenience only.
		fontsize : 12,  //NB set from css.
		lineheight : 12, // integer version derived from style sheet in setGlobals
		firstparagraphprev : 0
	});
	*/
	
}
/*********** Window KEY UP amd RESIZE ************************/
function windowKeyUp(evt)
{
	var iKey = getKeystroke(evt);
	var bShiftPressed = getShiftPressed(evt);
	var bAltPressed = getAltPressed(evt);
	var bCtrlPressed = getCtrlPressed(evt);

	//alert("the number of the key you hit is "+iKey);
	if (iKey == $.bm_main.KEY_TAB)
	{
		if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_CONFIRM_NEW_PASSWORD)
		{
			//alert("editing confirm new password");
		}
	}
	//NB Brian - alternate architecture involves dropping the variables, like EDITING_FIRST_NAME and 
	//instead querying the object which currently has the focus 
	//if ($($.bm_main.current_focus))
	//{alert("edit object has focus")}
	//else {alert("edit object doesn't have focus")};
	//alert($.bm_tab.current_edit_mode);
	//if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_NOTHING)  // if something is beinig edited ... 
	//{
		// Do nothing - fall through to bottom of function.
	//	alert("editing nothing");
	//}
	if (1==1)
	{
		// The enter key triggers a login event when the password or username fields are being edited.
		if (iKey==$.bm_main.KEY_ENTER)
		{
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_FIRST_NAME)
			{
				document.getElementById("last-name").focus();
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_LAST_NAME)
			{
				document.getElementById("city").focus();
				return;
			}

			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_CITY)
			{
				document.getElementById("email").focus();
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_EMAIL)
			{
				document.getElementById("preferences-save-button").focus();
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_USERNAME)
			{
				document.getElementById("password").focus();
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_PASSWORD)
			{
				//alert("here");
				login();
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_EXISTING_PASSWORD)
			{
				document.getElementById("new-password").focus();
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_NEW_PASSWORD)
			{
				document.getElementById("confirm-new-password").focus();
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_CONFIRM_NEW_PASSWORD)
			{
				preferencesUpdate();  //Should create a separate change password
				return;
			}
			if ($.bm_tab.current_edit_mode == $.bm_main.EDITING_PREFERENCES_UPDATE_PASSWORD_BUTTON)
			{
				preferencesUpdatePassword();  //Should create a separate change password
				return;
			}			
		}
		// tab. mostly rely on tabiindex ... 
		/*
		if (iKey==KEY_TAB) 
		{
			alert("tab pressed");
			if ($.bm_tab.current_edit_mode == EDITING_CONFIRM_NEW_PASSWORD)
			{
				alert("there");
				document.getElementById("preferences-save-button").focus(); 
				return;
			}			
		}
		*/
		// disable alpha shortcuts (A=65), like p for preferences. Alternatively add an extra key, like Ctrl p for previous.

		if (iKey>64 || iKey==$.bm_main.KEY_LEFT_ARROW || iKey == $.bm_main.KEY_RIGHT_ARROW)
		{
			if (bCtrlPressed)
			{ 
				// do nothing
				// Ctrl + keystroke yields results which happen regardless of edit state.
				//alert("here");
			} else
			{
				//alert("here");
				return;
			}
		}
	}
	/*
	if( window.getComputedStyle) 
	{
		// not IE
		key = evt.which;
		alert("debugging window keyup. You just pressed key "+key);	
	} else
	{
		key = event.keyCode;	
		alert("debugging Internet Explorer keypress event. You just pressed key "+key);	
	}
	*/
	//ctrl left arrow - previous page
	if ((iKey==$.bm_main.KEY_LEFT_ARROW && bCtrlPressed)) {$.colflow.previous()}
	//right arrow - next page
	if ((iKey==$.bm_main.KEY_RIGHT_ARROW && bCtrlPressed)) {$.colflow.next()}

	//down arrow  40 - go to end of story
	if ((iKey==$.bm_main.KEY_DOWN_ARROW && bCtrlPressed)) {
		$.colflow.setPage($.colflow.pageCount());
		$.colflow.drawPage();
	}
	//up arrow 38 - go to top of story
	if ((iKey==$.bm_main.KEY_UP_ARROW && bCtrlPressed)) {
		//NB Brian goto top and goto bottom don't quite work.
		$.colflow.setPage(0);
		$.colflow.drawPage();
	}
	//page down
	if (iKey==$.bm_main.KEY_PAGE_DOWN) {$.colflow.next()}
	//page up
	if (iKey==$.bm_main.KEY_PAGE_UP) {$.colflow.previous()}

	
	//r - 82 refresh
	if (iKey==82) {$.colflow.drawPage("resize")}
	//l - 76- login
	if (iKey==76) 
	{
		if (!$.bm_login.logged_in)
		{
			loginShow();
		}
	}
	return;
	//p - preferences
	if (iKey==80) 
	{
		if ($.bm_login.logged_in)
		{
			preferencesHideShow();
		}
	}
	//w - 87 - - wide / narrow toggle
	// Using keys like this creates work because control over editing is tightly controlled.
	if (iKey==67) {commentsHideShow()} /* c */
	if (iKey==72) {helpHideShow()} /* h */
	if (iKey==78) {$.colflow.next()} /* n */
}
// Initiate a complete redraw.
function windowResize()
{
	try
	{	
		if ($.colflow.template=="PHOTOS"){
			//test for screen size
			//adjust height of graphic			$.colflow.valignPicture();
			if ($.colflow.redrawFlag) {
				$.colflow.redrawFlag=false;
				setTimeout('drawPagePicture()',500);
			}
		}
		if ($.colflow.template=="STORIES"){	
			$.colflow.firstparagraphprev = $.colflow.firstParagraph($.colflow.page());
			//alert("se'ected "+$(".blind-menu.selected").attr("id"));
			setTimeout('$.colflow.drawPage("resize")',500);	
		}

		//drawPage("resize");
	}
	catch(err)
	{
		if ($.colflow.template){errorHandler("error in windowResize ",err)};
	}
}

/* ******** jQuery Event Handlers *********/

function setColorScheme(psWhichColor)
{
	$.colflow.colorscheme=psWhichColor; //This flag helps with event code related to tabs
	return;
	if (psWhichColor=="WHITE")
	{
		document.getElementById("body").style.backgroundColor="white";
		document.getElementById("body").style.color="black";

		document.getElementById("help-title").style.borderBottom="6px solid white";
		document.getElementById("help-inner").style.backgroundColor="white";
		document.getElementById("login-title").style.borderBottom="6px solid white";
		document.getElementById("login-inner").style.backgroundColor="white";
		document.getElementById("tab-mask").style.backgroundColor="white";
		//class menutab
		document.getElementById("help-title").style.color="black";
	}
	if (psWhichColor == "BLACK")
	{
		document.getElementById("body").style.backgroundColor="black";
		document.getElementById("body").style.color="white";
		document.getElementById("help-title").style.borderBottom="6px solid black";
		document.getElementById("help-inner").style.backgroundColor="black";
		document.getElementById("login-title").style.borderBottom="6px solid black";
		document.getElementById("login-inner").style.backgroundColor="black";	
		document.getElementById("tab-mask").style.backgroundColor="black";
		document.getElementById("help-title").style.color="white";
	}
}

function switchScheme(psWhichMode)
{
/*  to interface.js */
	$.colflow.template = psWhichMode;//STORIES PHOTOS POEMS ESSAYS VIDEOS ANIMATIONS

	// switch style sheets.
	//This function can be reduced to one line!
	//NBNB dock2 should be turned on and off with style sheet. This isn't working even though it is for dock.
	//Investigate and remove the offending code.
	if (psWhichMode =="PHOTOS")
	{
		$.colflow.colorscheme="BLACK";
		//switch style sheet //
		//alert("switch scheme");
		$('link[@rel*=style][title]').each(function() 
		{
			if (this.getAttribute('title') == "black.css") this.disabled = false;
			if (this.getAttribute('title') == "white.css") this.disabled = true;		
		});
		document.getElementById("icon-dock2").style.display="block";
	}
	if (psWhichMode == "STORIES")
	{
		$.colflow.colorscheme="WHITE";
		//switch style sheet //
		$('link[@rel*=style][title]').each(function() 
		{
			if (this.getAttribute('title') == "black.css") this.disabled = true;
			if (this.getAttribute('title') == "white.css") this.disabled = false;		
		});
		document.getElementById("icon-dock2").style.display="none";
	}
}

/***** Photograph Functions *****/
setResolution = function(psWhichResolution) {
	if (psWhichResolution=="800px")
	{
	};
	if (psWhichResolution=="600px")
	{
		//alert("here");
		document.getElementById("content").style.width = "900px";
		document.getElementById("header").style.top = "8px";
		document.getElementById("main-image").style.top = "16px";
		document.getElementById("main-image").style.width = "900px";
		document.getElementById("navbar").style.top = "630px";
		document.getElementById("navbar").style.left= "85px";
		document.getElementById("navbar").style.width = "650px";
		document.getElementById("slide-show").style.width = "630px";
		//document.getElementById("img-nav").style.width = "595px";
		document.getElementById("tab").style.left = "910px";
		document.getElementById("tab").style.top = "40px";
		document.getElementById("right_advert").style.left = "910px";
		document.getElementById("right_advert").style.top = "510px";
		document.getElementById("right_advert").style.height = "180px";
	};
	if (psWhichResolution=="400px")
	{
		document.getElementById("content").style.width = "600px";
		document.getElementById("navbar").style.top = "425px";
		document.getElementById("tab").style.left = "610px";
		document.getElementById("main-image").style.top = "50px";		
		document.getElementById("tab").style.top = "50px";
	};
	document.getElementsByClassName("replaced").height=psWhichResolution;
}

getCurrentImageIndex = function(){
	//redundant - carried in serialscroll pos property
	//can be determined using index property
	alert("in get CurrentImageIndex No longer needed!!");
	return $.colflow.current;
}
activateImage = function(piIndex) {
	//piIndex is the serialscroll index. 
	//$.colflow.activate($($.colflow.albumid).children("li").eq($.colflow.imageNumber()).children('img').attr('src'));
	alert("activate image "+$.colflow.image());
	$.colflow.activate($.colflow.image());
}
setImageIndex = function(piIndex){
	//NB Not called any more - useless until serial scroll can handle multiple slide shows.
	//make slideshow index the same as the galleria one
	//NBNB Need to handle an array of images.
	//alert("In setImageIndex");

	$("#slideshow-inner").trigger('setactive',[piIndex]);	
}


/** INITIALIZATION FUNCTIONS **************/
function setDefaults()
{
	try
	{

		//tocInit(); // NB initialize if using the drop down menu.
		//NB navbar dock
		//navbarInit();
		tocNavbarInit();

		//columnWidthInit();
		//helpShowSection(HELP_NAVIGATION);
		//preferencesShowSection(PREFERENCES_PERSONAL);
		//usernamePasswordEmailInit();
		//commentsInit();
		tocNavMouseOut(document.getElementById("toc-img"+$.colflow.chapterid));  
		//footerRightHideShow("none");  // NB Brian need to trigger off of table settings
		switchScheme("STORIES");
		if (LOCALHOST)  // helps my testing
		{

			document.getElementById("username").value = "bmacmill";
			document.getElementById("password").value = "nevsky";
			document.getElementById("login-submit-button").disabled = false;
		} else
		{

		document.getElementById("username").value = "<username>";
			document.getElementById("login-submit-button").disabled = false;
		}
		//document.getElementById("username").focus();
	} catch(err)
	{
		errorHandler("setDefaults",err);
	}
}

function setTOCTitles()
{
	try{
		$('#toc-navbar div').children('div').each(function(i) {
			if (i<6){
				$(this).children("img").attr("title", "Chapter "+Number(i+1)+": "+$("#book-"+$.colflow.bookid).children("div[name='c"+i+"']").attr("title"));
			} else {
				$(this).children("img").attr("title", $("#book-"+$.colflow.bookid).children("div[name='c"+i+"']").attr("title"));
			}
		});
	} catch(err)
	{errorHandler("setTOCTitles",err)}
}
function commentsInit()
{
	document.getElementById("your-comments").style.display="none";
	document.getElementById("comments-add-button").value = COMMENTS_ADD_BUTTON; // make constant for programming purposes
}

/********* END OF INITIALIZATION FUNCTIONS **************/
/********* EVENT HANDLERS ***********/
// NB to do - call from document.ready, not loaded(), except for elements loaded by php



function headertoggleEventHandler() 
{
	//note that the element needs to exist for this to work
	var e = document.getElementById('header-toggle');
	e.onmouseup = function() {headerHideShow();}	
}

// option events. mouse over, out and click.
// note that the options contains a number of nested elements
// trap for mouse up events on the next and previous elements.
function headerNavigationEventHandler() {
	//alert("in headerNavigationEventHandler");
	try
	{
		//NB Brian - should be done using class not id!!
		var sCurrentElementName;
		var e;
		sCurrentElementName="content-header-left-next";
		e = document.getElementById('content-header-left-next');
		e.style.display = "block";
		e.onmouseup = function() {$.colflow.next();}
		//e = document.getElementById('content-header-left-next-img');
		e.onmouseover = function() {navArrowOnMouseOver("content-header-left-next");}
		e.onmouseout = function() {navArrowOnMouseOut("content-header-left-next");}
		sCurrentElementName="content-header-right-next";
		e = document.getElementById('content-header-right-next');
		e.style.display = "block";
		e.onmouseup = function() {$.colflow.next();}
		//e = document.getElementById('content-header-right-next-img');
		e.onmouseover = function() {navArrowOnMouseOver("content-header-right-next");}		
		e.onmouseout = function() {navArrowOnMouseOut("content-header-right-next");}	
		sCurrentElementName="content-header-left-previous";
		e = document.getElementById('content-header-left-previous');
		e.style.display = "block";
		e.onmouseup = function() {$.colflow.previous();} 
		e.onmouseover = function() {navArrowOnMouseOver("content-header-left-previous");}		
		e.onmouseout = function() {navArrowOnMouseOut("content-header-left-previous");}	
		sCurrentElementName="content-header-right-previous";		
		e = document.getElementById('content-header-right-previous');
		e.style.display = "block";
		e.onmouseup = function() {$.colflow.previous();} 
		e.onmousover = function() {navArrowOnMouseOver("content-header-right-previous");}
		e.onmouseout = function() {navArrowOnMouseOut("content-header-right-previous");}
				

		e = document.getElementById('gutter');
		e.onmouseup = function(event) {gutterOnMouseUp(event);}

	} catch(err)
	{
		errorHandler("headerNavigationEventHandler element "+sCurrentElementName,err);
	}
}
function contentHeaderLeftEventHandler() {
	try
	{
		//note that the element needs to exist for this to work
		var e = document.getElementById('content-header-left-right');
		e.onclick = function() {contentHeaderLeftOnClick();}
	} catch(err)
	{
		errorHandler("contentHeaderLeftEventHandler ",err);
	}
}
function contentHeaderRightEventHandler() {
	try
	{
		//note that the element needs to exist for this to work
		var e = document.getElementById('content-header-right-left');
		e.onclick = function() {contentHeaderRightOnClick();}
	} catch(err)
	{
		errorHandler("HeaderRightEventHandler ",err);
	}
}

// stories are displayed within the content element
// note that content is a container for content inner, content text and column one/two
function contentEventHandler() {

	var e = document.getElementById('content');
	//e.onmouseup = function(event) {contentOnMouseUp(event);}

	e.onmouseover = function(event) {contentInnerOnMouseOver(event);}
	e.onmouseout = function(event) {contentInnerOnMouseOver(event)}
	e = document.getElementById('content-inner');
	e.onmouseover = function(event) {contentInnerOnMouseOver(event);}
	e.onmouseout = function(event) {contentInnerOnMouseOver(event)}
}
function contentInnerEventHandler() {
	//note that the element needs to exist for this to work
	var e = document.getElementById('content-inner');
	e.onmouseup = function(event) {contentInnerOnMouseUp(event);}
	//e.onmousedown = function(event) {contentInnerOnMouseDown(event);} 
	//e.ondrag = function(event) {contentInnerOnDrag(event);} 
}
function contentInnerOnDrag(event)
{
	//
	//Test if current position different from previous position. if so redraw page appropriately.	
}
function contentInnerOnMouseDown(evt)
{
	try
	{
		giMouseX = getPageX(evt);
	} catch(err)
	{
		errorHandler("Please excuse debugging message. Deployment in process.",err);
	}

	// trap current position for the sake of monitoring the drag direction of the mouse.
}
function contentInnerOnMouseUp(event)
{
	//is current position different from previous position?
}

function contentInnerOnMouseOver(event)
{
	/* NB Brian - to css */
	$.bm_main.previous_cursor_style = document.body.style.cursor;
	document.body.style.cursor = "default";	
}
function contentInnerOnMouseOut(event)
{
	document.body.style.cursor = $.bm_main.previous_cursor_style;	
}
function gutterOnMouseUp(pEvent)
{
	try
	{
		// if right mouse button is depressed
		if (window.getComputedStyle)
		{
			if (pEvent.which == 3) {return}
		} else
		{
		
			if (window.event.button == 2) {return}
		}
		if (getShiftPressed(pEvent))
		{
			$.colflow.previous();
		} else
		{
			$.colflow.next();			
		}
/*
		old way based on drag ... 
		var iPageX = getPageX(evt);
		var iResult = iPageX - giMouseX;


		if (Number(iResult)<= 0)
		{
			nextPage();
		} else if (Number(iResult)>1)
		{
			previousPage();
		}
		//alert("Content mouse up says move one page to the left " +giMouseX+" "+evt.pageX);		
		//alert("Content mouse up says move one page to the left " +iResult);
*/
	} catch(err)
	{
		//alert("Please excuse debugging message. Deployment in process.");
		errorHandler("gutterOnMouseUp",err);
	}
}

function navArrowOnMouseOver(psElementName)
{
	try
	{
		// NB Brian - to css :hover
		$.bm_main.previous_cursor_style = document.body.style.cursor;
		document.body.style.cursor = "pointer";
		if (document.getElementById(psElementName).src == ARROW_NEXT)
		{
			document.getElementById(psElementName).src == ARROW_NEXT_MOUSE_OVER;
		};
		if (document.getElementById(psElementName).src == ARROW_PREVIOUS)
		{
			document.getElementById(psElementName).src == ARROW_PREVIOUS_MOUSE_OVER;
		};
	} catch(err)
	{
		errorHandler("navArrowOnMouseOver",err);
	}
}
function navArrowOnMouseOut(psElementName)
{
	try
	{
		//NB Brian - to css
		document.body.style.cursor = $.bm_main.previous_cursor_style;
		if (document.getElementById(psElementName).src == ARROW_NEXT_MOUSE_OVER)
		{
			document.getElementById(psElementName).src == ARROW_NEXT;
		};
		if (document.getElementById(psElementName).src == ARROW_PREVIOUS_MOUSE_OVER)
		{
			document.getElementById(psElementName).src == ARROW_PREVIOUS;
		};
	} catch(err)
	{
		errorHandler("navArrowOnMouseOver",err);
	}
}
// Alternative code for trapping mouse events. Left as a reference
// To do: remove next two lines.
//function mouseX(evt) {if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;}
//function mouseY(evt) {if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;}

function footerEventHandler() 
{
	var d = document.getElementById('footer');
	d.style.display="block";
	d.onmouseup = function() {show_node_info();}		
}
// set story loaded flag to true - story is now loaded
function bookIsLoaded(piBookId) {
	//The idea here is to draw the first chapter after all of the chapters of the first book have been loaded.
	//The definition of loaded is the existence of the #first-book-is-loaded element
	//which is created after the php load script has fired.
	try{
		$.colflow.newBook(piBookId);
		setTOCTitles();
		$.colflow.drawPage("load");
	} catch(err) {
		errorHandler("bookIsLoaded",err);
	}
}
function imageAlbumIsLoaded()
{
	$.colflow.newImageAlbum("#"+$.bm_main.DEFAULT_IMAGE_ALBUM);
}
/**********  functions triggered by element events ************/

/**********  functions triggered by element events ************/

function contentHeaderLeftOnClick(evt)
{
	//showGlobals();
	//showColumnFormatingVars();
}
function contentHeaderRightOnClick(evt)
{

	//showGlobals();
	//showColumnFormatingVars();

}

/******************** END OF EVENT HANDLERS *****************/
/* 
 the loaded function tests to see if the element indicated by
 the first parameter has been loaded, and then attaches the event
 handling code indicated by the second argument.
*/

loadEventHandlers()
function loadEventHandlers()
{
	//Initiate event handlers as screen elements are loaded.
	try
	{
		//NB Most of this should be replaced by direct calls from document.ready.
		//The only exception are events that should be accessible before the page has loaded.
		loaded_two('first-book-is-loaded',bookIsLoaded,0);
		loaded($.bm_main.DEFAULT_SLIDESHOW_LOADED,imageAlbumIsLoaded);
	} catch(err)
	{
		errorHandler("LoadEventHandlers",err);
	}
}

window.onload = function() {
	try
	{
		$.bm_main.page_loaded = true;  //NB add to colflow class.
		//drawPage();
		//helpShow();
		//loginShow();
		setDefaults();
	} catch(err)
	{
		errorHandler("window.onload",err);
	}
}
window.onscroll = function(event){mouseScroll(event);}

function drawPage()
{
	$.colflow.drawPage("resize");
	
}


function drawPageSlideShow()
{
	//center image;
	$.colflow.valignPicture();
	$.colflow.redrawFlag = true;
	$.colflow.activate($.colflow.image())
}

function navShowChapter(e)
{	
	//NB Brian -hack - the images have a chapter number appended at the 8th digit.
	showChapter(e.id.substr(7,1));
}	
function showChapter(piChapter)
{
	try
	{
		//var element = document.getElementById(gasChapterElement[piChapter]);
		if ($.colflow.chapterid!=piChapter)
		{
			$.colflow.chapterid=piChapter;
			document.getElementById("title").text = "Brian MacMillan - " + $.colflow.chapterTitle(); 
			$.colflow.drawPage("switch");
			$.bm_comments.commentsGet($.colflow.bookid,$.colflow.chapterid);
			highlightCurrentChapterImage($.colflow.chapterid);
		}
	} catch(err)
	{
		errorHandler("showChapter: '",err);
	}
}


function addElement(piParagraphId) {
	try
	{
		var ni = document.getElementById('column-two');
		var new_p = document.createElement('p');
		new_p.innerHTML = "Test";
		ni.appendChild(new_p);
	}
	catch(err)
	{
		errorHandler("",err);
	}
}
function removeElement(divNum) {
   //new_p.innerHTML = 'Element Number '+num+' has been added! <a href=\'#\' onclick=\'removeElement('+pIdName+')\'>Remove the div "'+pIdName+'"</a>';
  var d = document.getElementById('myDiv');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}

function mouseScroll(event)
{
	//switch_page(event);
}
/* ******************************************************** */
// HIDE AND DISPLAY FOR TABS HIDE AND DISPLAY FOR TAB HIDE AND DISPLAY HIDE AND DISPLAY HIDE AND DISPLAY 
//Generic function to hide / display an element
function hide_show(elementName)
{
	alert("in hideshow to remove");
	e =  document.getElementById(elementName);
	try
	{
		if (e.style.display=="none")
		{
		 	e.style.display="block";
		} else 
		{
		 	e.style.display="none";	
		}
	}
	catch(err)
	{
	errorHandler("hide_show",err);
	}
}
/******** INTERFACE FUNCTIONS ******************/

function setColumnWidthEvent()
{
	try
	{
		setColumnWidth(giCurrentColWidth);
	} catch (err)
	{
		errorHandler("setColumnWidthEvent",err);
	}
}

/******** END INTERFACE FUNCTIONS ***********/
// display full option menu on mouse over.
// display full toc on mouse over.

/*
function getPageX(evt)
{
	if (window.getComputedStyle)
	{
		return evt.pageX; 
	} else
	{
		evt = window.event;
		return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); 
	}
}
*/



