// bm_main
//Todo NB BRIAN STOP THIS FROM BEING CALLED MULTIPLE TIMES in loadstories ... 
$(window).resize(function(){windowResize()});

// CSS and JS CONSTANTS to handle dynamic loading
var RATING = "js/jquery.rating/jquery.rating.js";
var RATING_ID = "jquery-rating";
var RATING_CSS = "css/jquery.rating.css";
var RATING_CSS_ID = "jquery-rating_css";

var SLIDESHOW = "js/bm/jquery.bm_ss.js";
var SLIDESHOW_ID = "bm_ss";

var PHOTOS_CONTAINER = "content-photos";
var PHOTOS_CSS = "css/bm_photos.css";
var PHOTOS_CSS_ID = "photos_css";
if (gbIE) {
	var PHOTOS_HTML = "html/photos_ie.html";
} else {
	var PHOTOS_HTML = "html/photos.html";
}
var PHOTOS_ROOT = "content-photos-inner";
//Poetry
var POETRY_SLIDESHOW_CONTAINER = "content-poems";
var POETRY_SLIDESHOW_HTML = "poems_slideshow.php";
var POETRY_SLIDESHOW_ROOT = "poems";

var POETRY_SLIDESHOW_CSS = "css/bm_poems.css";
var POETRY_SLIDESHOW_CSS_ID = "bm_poems_css";

//var POETRY_JS = "js/bm/bm_poems.js";
//var POETRY_JS_ID = "bm_poems";
var POETRY_JQUERY = "js/bm/jquery.bm_poems.js";
var POETRY_JQUERY_ID = "jquery_bm_poems";
// End poetry

var SERIAL_SCROLL = "js/serial_scroll/jquery.serial_scroll.js";
var SERIAL_SCROLL_ID = "serial_scroll";
var SCROLL_TO = "js/serial_scroll/jquery.scroll_to_min.js";
var SCROLL_TO_ID = "scroll_to";
// IE / NOT IE css
var NOT_IE_CSS = "css/not_ie.css";
var NOT_IE_CSS_ID = "not_ie_css";
// bm stories css
var STORIES_CSS_ID = "bm_stories_css";
var STORIES_CSS = "css/bm_stories.css";
var STORIES_CSS_ID = "bm_stories_css";
// bm stories
var COLFLOW = "js/bm/jquery.bm_colflow.js";
var COLFLOW_ID = "bm_colflow";
var DOCS = "js/bm/jquery.bm_documents.js";
var DOCS_ID = "bm_docs";
var NAVBAR = "js/bm/bm_navbar.js";
var NAVBAR_ID = "bm_navbar";
var STORIES = "js/bm/bm_stories.js";
var STORIES_ID = "bm_stories";
// tabs
var TAB_CSS = "css/tab.css";
var TAB_CSS_ID = "tab_css";
var ACCORDION = "js/tabs/accordion.js";
var ACCORDION_ID = "accordion";
var TAB = "js/tabs/jquery.bm_tabs.js";
var TAB_ID = "bm_tabs";
var IDTABS = "js/tabs/jquery.idtabs.js";
var IDTABS_ID = "idtab";
// icon dock
var IUTIL = "js/dock/jquery.iutil.js";
var IUTIL_ID = "iutil";
var IFISHEYE = "js/dock/jquery.ifisheye.js";
var IFISHEYE_ID = "ifisheye";
var IDOCK = "js/dock/jquery.icon_dock.js";
var IDOCK_ID = "icon_dock";
// general tools
var UI = "js/bm/jquery.bm_user_interface.js";
var UI_ID = "bm_ui";

var httpRequest;  // ajax object. dupe with jQuery.

var VIEWED_ABOUT = 1000;
var VIEWED_CONTACT = 1001;
var VIEWED_CV = 1002;
var VIEWED_ESSAYS = 1003;
var VIEWED_LINKS = 1004;
var VIEWED_LOGIN = 1005;

var VIEWED_PHOTOS = 1006;
var VIEWED_POEMS = 1007;
var VIEWED_STORIES = 1008;
var VIEWED_VIDEOS = 1009;

var loggedAbout = false;
var loggedContact = false;
var loggedCV = false;
var loggedEssays = false;
var loggedLinks = false;
var loggedLogin = false;
var loggedPhotos = false;
var loggedPoems = false;
var loggedStories = false;
var loggedVideos = false;
var CLICK_TO_VIEW = "Click image to activate slideshow.";

if (gbIE)
{
	httpRequest =  new ActiveXObject("Microsoft.XMLHTTP");
} else
{
	httpRequest = new XMLHttpRequest();
}
/*
if (window.XMLHttpRequest)
{
	httpRequest = new XMLHttpRequest();
} else
{
	httpRequest =  new ActiveXObject("Microsoft.XMLHTTP");
}
*/
var bFirstTime = true;

documentReadyMain = function(){
	//called when main.php is loaded
	bHide=true;
	
	//create events for menus
	//anchor elements are used for IE because divs don't have an inline-block property
	if (gbIE) 
	{
		$("#main-menu a").click(function() {mainMenuClick(this)});
	} else
	{
		$("#main-menu div").click(function() {mainMenuClick(this)});
	}
	$("#content-homepage a.v-link").mouseover(function() {mainSubmenuMouseOver(this)});
	$("#content-homepage a.v-link").click(function() {mainSubmenuClick(this)});

	$("#main-submenu a.h-link").mouseover(function() {mainSubmenuMouseOver(this)});
	$("#main-submenu a.h-link").click(function() {mainSubmenuClick(this)});
	
	$(".homepage .submit").click(function() {homepageSubmitClick(this)});
	$(".homepage img").click(function() {homepageSubmitClick(this)});

	mainSubmenuClick($(".essays .h-link.active"));
	mainSubmenuClick($(".photos .h-link.active"));
	mainSubmenuClick($(".poems .h-link.active"));
	mainSubmenuClick($(".stories .v-link.active"));
	mainSubmenuClick($(".videos .h-link.active"));
	
	$(".homepage.about").addClass("active");
	
	switchScheme("DEFAULT");

	//NB the container for an element has the prefix #div-home-page. The element itself has no prefix, eg contact-submit

	$("#contact-submit").keypress(function(event){contactSubmitKeypress(event)});
	$("#contact-submit").click(function() {contactSubmit()});
	//$("#contact-email-address").blur(function() {$.bm_users.validateEmail(this,true,"#contact-message")});
	//$("#contact-email-address").focus(function() {$.bm_users.validateEmailFocus(this)});

	$("#contact-email-cc").blur(function() {$.bm_users.validateEmail(this,false,"#contact-message")});

	$.bm_logs.logEvent(0); // 0 = anonymous visit to homepage
	//loadPoemDependencies();  /*preload for speed */

	
	loadPhotoDependencies();
	loadStoryDependencies();

	if (gbIE) {
		ieEventHandler();
	}
	
	bFirstTime = false;
	

}
ieEventHandler = function(){
	//custom event handlers for ie8 - a:hover not working
	$("#homepage-stories-menu a.v-link").hover(
  	function () {
		$.bm_ui.setCursor("pointer");
	  }		
	)
	$("#homepage-stories-menu a.v-link").mouseleave(
  	function () {
		$.bm_ui.setCursor("default");
	  }		
	)
	//$("#homepage-stories-menu a.v-link").mouseout($.bm_ui.setCursor("default");)
}
mainMenuClick = function(e){
	/* click on about cv essays ... contact menu options */

	hideAll();

	if ($(e).text()!="STORIES") $("#main-header").addClass("active");

	// give active menu a distinctive color
	$(e).siblings().removeClass("active");
	$(e).addClass("active");
	
	switch ($(e).text()){
		case "about":
			switchScheme("DEFAULT");
			$("#homepage").addClass("active");
			$(".homepage.about").addClass("active");
			if (!loggedAbout){
				$.bm_logs.logEvent(VIEWED_ABOUT);
				loggedAbout=true;
			}
			break;
		case "cv":
			switchScheme("BIO");
			$("#homepage").addClass("active");
			$(".homepage.bio").addClass("active");
			if (!loggedCV){
				$.bm_logs.logEvent(VIEWED_CV);
				loggedCV=true;
			}
			break;
		case "essays":	
			switchScheme("DEFAULT");
			$("#homepage").addClass("active");
			$(".homepage.essays").addClass("active");
			$("#main-submenu .essays.link-container").addClass("active");
			if (!loggedEssays){
				$.bm_logs.logEvent(VIEWED_ESSAYS);
				loggedEssays=true;
			}
			break;
		case "contact":
			switchScheme("DEFAULT");
			$("#homepage").addClass("active");
			$(".homepage.contact").addClass("active");
			if (!loggedContact){
				$.bm_logs.logEvent(VIEWED_CONTACT);
				loggedContact=true;
			}
			break;
		case "links":
			switchScheme("DEFAULT");
			$("#homepage").addClass("active");
			$(".homepage.links").addClass("active");
			if (!loggedLinks){
				$.bm_logs.logEvent(VIEWED_LINKS);
				loggedLinks=true;
			}
			break;
		case "log-in":
			switchScheme("DEFAULT");
			$(".homepage.login").addClass("active");
			$.bm_users.eventHandler();
			if (!loggedLogin){
				$.bm_logs.logEvent(VIEWED_LOGIN);
				loggedLogin=true;
			}
			break;
		case "photos":
			switchScheme("DEFAULT");
			$("#homepage").addClass("active");
			$(".homepage.photos").addClass("active");
			$("#main-submenu .photos.link-container").addClass("active");
			if (!loggedPhotos){
				$.bm_logs.logEvent(VIEWED_PHOTOS);
				loggedPhotos=true;
			}
			break;
		case "poems":
			loadPoems();
			if (!loggedPoems){
				$.bm_logs.logEvent(VIEWED_POEMS);
				loggedPoems=true;
			}
			break;
		case "stories":
			switchScheme("DEFAULT");
			$("#homepage").addClass("active");
			$(".homepage.stories").addClass("active");
			/* ie exception */
			$("#homepage-stories-menu").addClass("active");
			/* moz version */
			$("#main-submenu .stories.link-container").addClass("active");
			if (!loggedStories){
				$.bm_logs.logEvent(VIEWED_STORIES);
				loggedStories=true;
			}
			break;
		case "videos":
			switchScheme("DEFAULT");
			$(".homepage.videos").addClass("active");
			$("#main-submenu .videos.link-container").addClass("active");
			if (!loggedVideos){
				$.bm_logs.logEvent(VIEWED_VIDEOS);
				loggedVideos=true;
			}
			break;
	}
	vAlignHomepage();
}
setMainMenuItem = function (psWhichItem)
{
	$("#main-menu div").removeClass("active");
	//NB Hardwired reference - eq(1) is the photos link. Bleech. Add id reference. That'll be safer.
	$("#main-menu div").eq(3).addClass("active");
	$("#main-submenu div").removeClass("active");
	$("#main-submenu div.photos").addClass("active");
	$("#main-submenu div.photos a.hlink").eq(3).addClass("active");
}
mainSubmenuMouseOver = function(e)
{
	return; //not active yet.
}
mainSubmenuClick = function(e){
	// remove and add active class to appropriate menu items and related images.
	// for example, when you click on stories, the stories tab appears 
	// as does a book cover thumbnail and a submenu.

	$(e).siblings().removeClass("active");
	$(e).addClass("active");
	if ($(e).hasClass("essays")){
		$("#homepage-essays .image-container img").removeClass("active");
		$("#homepage-essays .image-container img").eq($(".essays.link-container a").index($(e))).addClass("active");
		$("#homepage-essays .abstract").text($(e).attr("abstract"));
	}
	if ($(e).hasClass("photos")){

		$("#homepage-photos .image-container img").removeClass("active");
		
		$("#homepage-photos .image-container img").removeClass("active");
		$("#homepage-photos .image-container img").eq($(".photos.link-container a").index($(e))).addClass("active");
		$("#homepage-photos .abstract").text($(e).attr("abstract")+". "+CLICK_TO_VIEW);

		//NB To do - make the header page for each slideshow the first image in the slideshow, perhaps.
		//this eliminates one click.
		$(".content.photos.active").removeClass("active");
		if (!bFirstTime) {
			// only trigger when navigating from a loaded slideshow, not on page load.
			$(".homepage.photos.container").addClass("active");
		}
	}
	if ($(e).hasClass("poems")){
		$(".homepage.poems .image-container img").removeClass("active");
		$(".homepage.poems .image-container img").eq($("#homepage-poems a").index($(e))).addClass("active");
		$("#homepage-poems .abstract").text($(e).attr("abstract"));
	}
	if ($(e).hasClass("stories")){
		$("#homepage-stories .image-container img").removeClass("active");
		$("#homepage-stories .image-container img").eq($(".stories.link-container a").index($(e))).addClass("active");
		$("#homepage-stories .abstract").text($(e).attr("abstract"));
	}
	if ($(e).hasClass("videos")){
		$("#homepage-videos .image-container div").removeClass("active");
		$("#homepage-videos .image-container div").eq($(".videos.link-container a").index($(e))).addClass("active");
		$("#homepage-videos .abstract").text($(e).attr("abstract"));
	}
	return;
}
homepageSubmitClick = function(e) {
	if ($(e).hasClass("essays") || $(e).parent().hasClass("essays") || $(e).parent().parent().hasClass("essays")){
		loadEssays($(e).attr("id"));
	}
	
	if ($(e).hasClass("photos") || $(e).parent().hasClass("photos")){
		var sTitle = $("a.photos.active").text();
		switch ($("a.photos.active").text())
		{
			case "abstract":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Abstract Photographs, 1999-present",1);
				break;
			case "animals":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs of Animals, 1999-present",1);
				break;
			case "celebrations":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs of Weddings and Bar/Bat Mitzvahs, 2001-present",1);
				break;
			case "clouds":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs of Clouds, 1999-present",1);
				break;
			case "dance":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Dance Photographs, 2003-present",1);
				break;
			case "graffiti":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs of Graffiti, 2003-present",1);
				break;
			case "homeless":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs of Homeless People and Beggars, 2003-present",1);
				break;
			case "hyper-real":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Dance Photographs, 2003-present",1);
				break;
			case "india":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's India Photographs, 2001-2007",1);
				break;
			case "italy":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs from Italy, 2002",1);
				break;
			case "mexico":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs from Oaxaca, 2010",1);
				break;
			case "nature":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Nature Photographs, 2000-present",1);
				break;
			case "ny":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's NY Photographs, 1999-present",1);
				break;
			case "parades":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs of Parades, 2003-present",1);
				break;
			case "people":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs of People, 2003-present",1);
				break;
			case "peru":
				loadPhotos($("a.photos.active").text()+"-400px","Brian MacMillan's Photographs from Peru, 2004, 2009",1);
				break;
			case "thesis":
				loadPhotos($("a.photos.active").text()+"-400px","Stills from Brian MacMillan's Master's Thesis Project, 2009",1);
				break;
		}
	}
	if ($(e).hasClass("poems") || $(e).parent().hasClass("poems")){
		//alert("show poems");
		loadPoems(e);
	}
	if ($(e).hasClass("stories") || $(e).parent().hasClass("stories")){
		switchScheme("DEFAULT");
		
		switch ($(e).attr("id"))
		{
			case "brains-img":
				loadStories("stories/when-we-all-have-brains.html");
				break;
			case "rebirth-img":
				loadStories("stories/rebirth.html");
				break;
			case "crust-monster-img":
				loadStories("stories/rebirth.html");
				break;
			case "mr-market-img":
				loadStories("stories/mr_market.html");
				break;
			case "shopaholic-img":
				loadStoriesSimple("stories/shopaholic-goes-to-calcutta.html");
				break;
			case "first-chapters-img":
				loadStories("stories/rebirth.html");
				break;
		}
	}
	if ($(e).hasClass("videos")){
		//alert("show videos");		
	}
}
	loadPhotoDependencies = function(){
		
		//if ($("#"+SLIDESHOW_ID).size()==0){loadFile(SLIDESHOW,"js",SLIDESHOW_ID)};
		if ($("#"+SLIDESHOW_ID).size()==0){loadFile(SLIDESHOW,"js",SLIDESHOW_ID)};

		if ($("#"+RATING_ID).size()==0){loadFile(RATING,"js",RATING_ID)};
		if ($("#"+RATING_CSS_ID).size()==0){loadFile(RATING_CSS,"css",RATING_CSS_ID)};
		
		
		//if ($("#"+PHOTOS_CSS_ID).size()==0){loadFile(PHOTOS_CSS,"css",PHOTOS_CSS_ID)};

	}
	getCategoryIndexFromTitle = function(psTitle){
		if (psTitle=="abstract") return 1;
		if (psTitle=="animals") return 14;
		if (psTitle=="celebrations") return 17;
		if (psTitle=="clouds") return 6;
		if (psTitle=="dance") return 5;
		if (psTitle=="graffiti") return 7;
		if (psTitle=="homeless") return 15;
		if (psTitle=="hyper-real") return 16;
		if (psTitle=="india") return 2;
		if (psTitle=="italy") return 13;
		if (psTitle=="mexico") return 12;
		if (psTitle=="nature") return 4;
		if (psTitle=="ny") return 8;
		if (psTitle=="parades") return 9;
		if (psTitle=="peru") return 10;
		if (psTitle=="people") return 3;
		if (psTitle=="thesis") return 11;
	}
	vAlignHomepage = function(){
		//alert("in valignhompage");
		return;
		var iContentHeight = Number($("#content-homepage-inner").attr("clientHeight"));
		var iPageHeight = Number($("body").attr("clientHeight"));
		iTop=(iPageHeight-iContentHeight);
		iTop=iTop/2;
		$("#main").css({top:iTop});

	}

/* HOMEPAGE */
loadHomepage = function(psShow){
	hideAll();
	switchScheme("DEFAULT");
	$(".content.homepage").addClass("active");	
	if (psShow =="STORIES"){$(".homepage.stories").addClass("active");}
	$("#main-header").addClass("active");
}
/* ESSAYS */
loadEssays = function(psEssayImage){
	switch(psEssayImage){
	case "deva-image":
		//if asura and devas essay hasn't been loaded, load it.
		break;
	case "negation-image":
		//if asura and devas essay hasn't been loaded, load it.
		break;
	}
}
/* END ESSAYS */
/* PHOTOS Slideshow */
loadPhotos = function(psContainer,psTitle,piIndex)
{
	try
	{
		//alert("in load photos");
		var _ss_parent = "#content-photos-inner";
		$(".homepage.photos.active").removeClass("active");
		//hideAll();
		
		//alert("in loadPhotos");
		$.bm_ui.template="PHOTOS";
		/*
		if ($("#"+SLIDESHOW_ID).size()==0){loadFile(SLIDESHOW,"js",SLIDESHOW_ID)};
		*/
		var bUseRating = false;
		if (bUseRating){
			if ($("#"+RATING_ID).size()==0){loadFile(RATING,"js",RATING_ID)};
			if ($("#"+RATING_CSS_ID).size()==0){loadFile(RATING_CSS,"css",RATING_CSS_ID)};
		}
		//if ($("#"+SLIDESHOW_ID).size()==0){loadFile(SLIDESHOW,"js",SLIDESHOW_ID)};
		//if ($("#"+PHOTOS_CSS_ID).size()==0){loadFile(PHOTOS_CSS,"css",PHOTOS_CSS_ID)};
		/*
		if ($("#"+SCROLL_TO_ID).size()==0){loadFile(SCROLL_TO,"js",SCROLL_TO_ID)};
		if ($("#"+SERIAL_SCROLL_ID).size()==0){loadFile(SERIAL_SCROLL,"js",SERIAL_SCROLL_ID)};
		if ($("#"+PHOTOS_CSS_ID).size()==0){loadFile(PHOTOS_CSS,"css",PHOTOS_CSS_ID)};
		*/
		if ($("#"+UI_ID).size()==0){loadFile(UI,"js",UI_ID)};
		setTimeout("loadPhotos2()",200);
	} catch(err)
	{
		errorHandler("bm_main.loadPhotos",err);
	}
}
loadPhotos2 = function(){
	//initialize the slideshow
	//append slideshow.html to content-photos 
	var sTitle = $("a.photos.active").text();
	$.ss.resolution = "400";
	$.ss.current_category = getCategoryIndexFromTitle(sTitle);
	$.bm_ui.title=sTitle;
	document.title = $.bm_ui.title;
	//alert("in load photos2 - debugging deployment");
	if (!document.getElementById(PHOTOS_ROOT)){
		$("#"+PHOTOS_CONTAINER).load(PHOTOS_HTML,
			function (responseText, textStatus, XMLHttpRequest) {
			if (textStatus=="success") {
				$(".rating").rating({showCancel: false});
				$.ss.getSlideshowFromDatabase();
				initializePhotos();
			} else {
				alert("Error: failed to load '"+psContainer+"'");
				return;
			}
		});
	} else{
		//alert("loadphotos2 category "+$.ss.current_category);
		$.ss.getSlideshowFromDatabase();
	}
	switchScheme("PHOTOS");
}
	initializePhotos = function(){
		// Initialize the click events
		var _ss_parent = "#content-photos-inner";
		if (gbIE) {
			$(_ss_parent+" #slideshow-arrow-left").click(function() {$.ss.previous(this)})
			$(_ss_parent+" #slideshow-arrow-right").click(function() {$.ss.next(this)})
			// Initialize hover
			var _ss_parent = "#content-photos-inner";
			$(_ss_parent+" #slideshow-arrow-left").mouseover(function() {$.ss.navMouseOver(this)})
			$(_ss_parent+" #slideshow-arrow-right").mouseover(function() {$.ss.navMouseOver(this)})

			$(_ss_parent+" #slideshow-arrow-left").mouseout(function() {$.ss.navMouseOut(this)})
			$(_ss_parent+" #slideshow-arrow-right").mouseout(function() {$.ss.navMouseOut(this)})

		} else
		{
			$(_ss_parent+" .navigation a.arrow.previous").click(function() {$.ss.previous(this)})
			$(_ss_parent+" .navigation a.arrow.next").click(function() {$.ss.next(this)})
		}
	}
/* END Photo Slideshow */

/**** POEMS ***/
loadPoems = function(e)
{
	try
	{

		$.bm_ui.template="POEMS";
		$.bm_ui.title="Brian  MacMillan Selected Poems";
		document.title = $.bm_ui.title;

		if ($("#"+POETRY_SLIDESHOW_CSS_ID).size()==0){
			// NB: log this error
			loadFile(POETRY_SLIDESHOW_CSS,"css",POETRY_SLIDESHOW_CSS_ID)
			};
		//if ($("#"+SCROLL_TO_ID).size()==0){loadFile(SCROLL_TO,"js",SCROLL_TO_ID)};
		//if ($("#"+SERIAL_SCROLL_ID).size()==0){loadFile(SERIAL_SCROLL,"js",SERIAL_SCROLL_ID)};
		//if ($("#"+POETRY_JQUERY_ID).size()==0){loadFile(POETRY_JQUERY,"js",POETRY_JQUERY_ID)};
		$(".homepage.poems").addClass("active");
		$(".content.poems").addClass("active");
		loadPoems2();
	} catch(err)
	{
		errorHandler("bm_main.loadPoems",err);
	}
}
	loadPoems2 = function(){
		//initialize the slideshow
		//append slideshow.html to content-photos 
		if (!document.getElementById(POETRY_SLIDESHOW_ROOT)){
			$("#"+POETRY_SLIDESHOW_CONTAINER).load(POETRY_SLIDESHOW_HTML,
				function (responseText, textStatus, XMLHttpRequest) {
				if (textStatus=="success") {
					switchScheme("POEMS");
					hideAll();
					loaded(SERIAL_SCROLL_ID,initializePoems);
				}
			});
		} else
		{
			hideAll();
			poemsDisplay();
		}
	}
	poemsDisplay = function(){
		switchScheme("POEMS");
		$(".content.poems").addClass("active");
		$(".content.homepage").addClass("active");
		$("#homepage").removeClass("active");
	}
	loadPoemDependencies = function(){
	
		if ($("#"+POETRY_SLIDESHOW_CSS_ID).size()==0){loadFile(POETRY_SLIDESHOW_CSS,"css",POETRY_SLIDESHOW_CSS_ID)};
		$('link[@rel*=style][id]').each(function() 
		{
			if (this.getAttribute('id') == POETRY_SLIDESHOW_CSS_ID) {this.disabled = true};
		});
	//	if ($("#"+SCROLL_TO_ID).size()==0){loadFile(SCROLL_TO,"js",SCROLL_TO_ID)};
	//	if ($("#"+SERIAL_SCROLL_ID).size()==0){loadFile(SERIAL_SCROLL,"js",SERIAL_SCROLL_ID)};
		if ($("#"+POETRY_JQUERY_ID).size()==0){loadFile(POETRY_JQUERY,"js",POETRY_JQUERY_ID)};
	}
	initializePoems = function(){
		try{
			$("#poems").serialScroll({
				target:'#poems-text',
				items:'li', // Selector to the items ( relative to the matched elements)
				axis:'x',// The default is 'y' scroll on both ways
				//prev:'img.prev_off',// Selector to the 'prev' button (absolute!, meaning it's relative to the document)
				//next:'img.next_off',// Selector to the 'next' button (absolute too)
				navigation:'#poems-navigationx .arrow-container a',
				duration:1000 ,// Length of the animation (if you scroll 2 axes and use queue, then each axis take half this time)
				force:true, // Force a scroll to the element specified by 'start' (some browsers don't reset on refreshes)
				start: 0,
				lock: true,
				lazy: true,
				constant: true,
				onBefore:function( e, elem, $pane, $items, pos ){
					/**
					 * 'this' is the triggered element 
					 * e is the event object
					 * elem is the element we'll be scrolling to
					 * $pane is the element being scrolled
					 * $items is the items collection at this moment
					 * pos is the position of elem in the collection
					 * if it returns false, the event will be ignored
					 */
					 //those arguments with a $ are jqueryfied, elem isn't.
					//return false; //NBNB temporary This disables the next
					//alert("in on before");
					if ($.bm_poems.cancel_serial_scroll) {return false}
					e.preventDefault();
					if( this.blur )
						this.blur();
				},
				onAfter:function( elem ){
					poemsOnAfter(elem);
				}
			});
			/*
			$($.bm_poems.selector).bm_poems({
				poemid : 0,
				history : true, // activates the history object for bookmarking, back-button etc.
				clickNext : true, // helper for making the image clickable
				onPoem : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
					//do stuff
				}
			}); */
			setTimeout("initializePoemsTwo();",2);
		} catch(err)
		{
			errorHandler("initializePoems",err);
		}
	}
	initializePoemsTwo = function(){
		$("#poems-navigation a.arrow.next").click(function() {$.bm_poems.next(this)});
		$("#poems-navigation a.arrow.previous").click(function() {$.bm_poems.previous(this)});

		$("#poems-toc-navigation li a").click(function() {$.bm_poems.goto(this)});
		$("#poems-toc-navigation ul span").click(function() {$.bm_poems.TOCClick(this)})

		//NB To fix - this keyup will step on stories keyup Need to merge.
		/*
		if (!gbIE)
		{
			window.onkeyup = function(event) {poemsWindowKeyUp(event);}
		} else
		{
			document.onkeyup = poemsWindowKeyUp;	
		}
		*/
		$('#poetry-toc-header').click(function(){
			$.bm_poems.TOCClick();
		});
		poemsDisplay();
	}
	poemsOnAfter = function(elem){
		//alert("in poemsOnAfter");
	}
/* END Poems*/

loadStories = function(psWhichStory){
	document.body.style.cursor ="wait";
	if (safari) {
		//alert("safari fix in loadstories");
		//$("#bm_main_css").attr("disabled",true);
		//alert("style sheet property "+$("#bm_stories_css").attr("disabled"));
		//$("#bm_stories_css").attr("disabled",false);
	}
	$("#homepage-stories").removeClass("active");
	$("#main-header").removeClass("active");
	$.bm_ui.template="STORIES";
	
	// load css and js dependencies if they have not been loaded
	loadStoryDependencies();
	
	// NB Can't continue until $.colflow is loaded.
	loaded_two(COLFLOW_ID,loadStories2,psWhichStory);
	//alert("stories have bene loaded");

}
	loadStoryDependencies = function(){
		// load css and js dependencies for the stories menu
		if ($("#"+COLFLOW_ID).size()==0){loadFile(COLFLOW,"js",COLFLOW_ID)};
		if ($("#"+UI_ID).size()==0){loadFile(UI,"js",UI_ID)};


		if ($("#"+DOCS_ID).size()==0){loadFile(DOCS,"js",DOCS_ID)};
		if ($("#"+STORIES_ID).size()==0){loadFile(STORIES,"js",STORIES_ID)};
		if ($("#"+NAVBAR_ID).size()==0){loadFile(NAVBAR,"js",NAVBAR_ID)};
		if ($("#"+IUTIL_ID).size()==0){loadFile(IUTIL,"js",IUTIL_ID)};

		// icon-dock
		if ($("#"+IFISHEYE_ID).size()==0){loadFile(IFISHEYE,"js",IFISHEYE_ID)};
		//NB Clash with serial scroll, apparently not needed
	 	//if ($("#"+IDOCK_ID).size()==0){loadFile(IDOCK,"js",IDOCK_ID)};
		// tabs
		if ($("#"+ACCORDION_ID).size()==0){loadFile(ACCORDION,"js",ACCORDION_ID)};
		if ($("#"+TAB_ID).size()==0){loadFile(TAB,"js",TAB_ID)};
		if ($("#"+IDTABS_ID).size()==0){loadFile(IDTABS,"js",IDTABS_ID)};

		if ($("#"+TAB_CSS_ID).size()==0){loadFile(TAB_CSS,"css",TAB_CSS_ID);}
		// bm_stories_css
		if ($("#"+STORIES_CSS_ID).size()==0){
			loadFile(STORIES_CSS,"css",STORIES_CSS_ID);
			}
	}
loadStories2 = function(psWhichStory){
	// IE To add
	/*
	if (gbIE) 
	{
		loadStoriesIE(psWhichStory);
		return;
	}
	*/
	if ($(".story-source").size()==0){
		documentReadyStories();
	}
	//clear column-one and column-two text
	switch (psWhichStory)
	{
		case "stories/when-we-all-have-brains.html":
			if ($("#ct0").size()>0){loadStories3();return;}
			var _div = $(document.createElement('div')).attr("id","ct0");
			$(_div).addClass("story-source");
			$('#content-text-inner').append(_div);
			
			//$('#content').append($('<section>').attr('id', 'about').html('<h1>About Us</h1><p>some text</p>'));
			
			$("#ct0").load(psWhichStory,
				function (responseText, textStatus, XMLHttpRequest) 
				{
					if (textStatus=="success")
					{	
						if (safari) {
							//Trick to finish the load
							var block = document.body.offsetWidth;
							//delay(5000);
							}
						bookIsLoaded(0);
						loadStories3();
					} else
					{
						errorHandler("bm_main loadStories - load status = "+textStatus);
					}
				}
			);
			break;
		case "stories/rebirth.html" :
			if ($("#ct1").size()>0){loadStories3();return;}
			var _div = $(document.createElement('div')).attr("id","ct1");
			$(_div).addClass("story-source");
			$('#content-text-inner').append(_div);			
			$("#ct1").load(psWhichStory,
				function (responseText, textStatus, XMLHttpRequest) 
				{
					if (textStatus=="success")
					{	
						bookIsLoaded(1);
						loadStories3();
					} else
					{
						errorHandler("bm_main loadStories - load status = "+textStatus);
					}
				}
			);
			break;
	}
}
loadStories3 = function(){
	$("#column-one").text("");
	$("#column-two").text("");
	$(".content.homepage").removeClass("active");
	$("#main-header").removeClass("active");
	$(".content.stories").addClass("active");
	//NB windowResize is tricky. Don't let it be called multiple times. 
	$(window).resize(function(){windowResize()});
	windowResize();
	document.body.style.cursor ="default";
	switchScheme("STORIES");
	setTimeout("positionIconDock()",1000);

	if (safari) {
		//alert("safari test in loadStories3");
		//setTimeout("location.reload;",10000);
	}
}
loadStoriesIE = function(psWhichStory)
{
	//dynamically load css style sheet for IE. it contains overrides
	//for settings in other css files and needs to be loaded last.
	//http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
	var headID = document.getElementsByTagName("head")[0];         
	var cssNode = document.createElement('link');
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	cssNode.href = 'css/ie.css';
	cssNode.media = 'screen';
	headID.appendChild(cssNode);
	alert("in loadStoriesIE");
	$("body").load("main_ie.php",
		function (responseText, textStatus, XMLHttpRequest) {
		if (textStatus=="success") {
			$("#ct0").load(psWhichStory,
			function (responseText, textStatus, XMLHttpRequest) 
				{
					if (textStatus=="success")
					{	
						$("#ct0").append("<div");
						//$("#ct0 div:last-child").attr("id","first-book-is-loaded");
						
						bookIsLoaded(0);
						
						//setTimeout('$.colflow.drawPage("resize");positionIconDock();',500);	
						//$.colflow.drawPage("resize");
						positionIconDock();
						//$("#ct0").hide();
					} else
					{
						alert("textStatus "+textStatus);
					}
				}
			)
		} else {
			errorHandler("bm_main loadStoriesIE - load status = "+textStatus);
			return;
		}
	});	
}
/* END STORIES */
/* UTILTIES */
poemsWindowKeyUp = function(evt)
{
	alert("in poemsWindowKeyUp");
	var iKey = getKeystroke(evt);
	var bShiftPressed = getShiftPressed(evt);
	var bAltPressed = getAltPressed(evt);
	var bCtrlPressed = getCtrlPressed(evt);
	//ctrl left arrow - previous page
	if ((iKey==$.bm_ui.KEY_LEFT_ARROW && bCtrlPressed)) {$.bm_poems.previous()}
	//right arrow - next page
	if ((iKey==$.bm_ui.KEY_RIGHT_ARROW && bCtrlPressed)) {$.bm_poems.next()}

	//down arrow  40 - go to last poem
	if ((iKey==$.bm_ui.KEY_DOWN_ARROW && bCtrlPressed)) {

	}
	//up arrow 38 - go to first poem
	if ((iKey==$.bm_ui.KEY_UP_ARROW && bCtrlPressed)) {

	}
	if (iKey==$.bm_ui.KEY_PG_DN) {$.bm_poems.next()}

	if (iKey==$.bm_ui.KEY_PG_UP) {$.bm_poems.previous()}

}
windowResize = function()
{
	try
	{	
		// NB Brian Tricky exception handling
		// Switching tabs on the browser was firing the resize event
		// I was trying to stop that and found that simply 
		// referring to the window name property stopped the resize from firing 
		// during a window onblur (lost focus) event on
		// firefox on windows. I cannot explain this.
		// To do, perhaps, create a window on focus / blur flag which causes the
		// below code to fire on focus, not on blur.
		var s = window.name;

		//document.title="windowResize plus template "+$.bm_ui.template;
		//var s = window.document.title;
		//if (s.substring(0,5) != "Brian") return;		
		
		if ($.bm_ui.template=="POEMS"){
			//test for screen size
			//adjust height of graphic
			//$.colflow.valignPicture();
			if ($.bm_ui.redrawFlag) {
				$.bm_ui.redrawFlag=false;
				//setTimeout('drawPagePicture()',500);
			}
		}
		if ($.bm_ui.template=="PHOTOS"){
			//test for screen size
			//adjust height of graphic
			//$.colflow.valignPicture();
			if ($.colflow.redrawFlag) {
				$.colflow.redrawFlag=false;
				setTimeout('drawPagePicture()',500);
			}
		}
		if ($.bm_ui.template=="STORIES"){	
			$.colflow.firstparagraphprev = $.colflow.firstParagraph($.colflow.page());
			//alert("in window resize selected "+$(".blind-menu.selected").attr("id"));
			$.colflow.redraw_in_progress=true;
			$.colflow.cancel_event=false;
			setTimeout('afterWindowResizeStories()',200);	
		}

		//drawPage("resize");
	}
	catch(err)
	{
		if ($.bm_ui.template){errorHandler("Error in bm_main.windowResize ",err)};
	}
}
	afterWindowResizeStories = function(){
		//The idea is that if this function is called by a resize event the redraw_in_progress flag is true; if called 
		//by itself and there has not been a resize event then the redraw_in_progress flag is false and the redraw code can be called.
		//In order to work the timing on setTimeout in afterWindowResizeStories needs to be greater than the setTimeout in windowResize.
		//cancel_event is used to stop drawPage from firing more than once should a number of calls to this function occur once the 
		//redraw_in_progress flag is set to false.

		if ($.colflow.cancel_event) return;
		if (!$.colflow.redraw_in_progress) {$.colflow.drawPage("resize");positionIconDock();$.colflow.cancel_event=true;} else {setTimeout('afterWindowResizeStories()',800);}
		//document.write("iafterWindowResizeStories");
		$.colflow.redraw_in_progress=false;
		//document.title="in afterWindowResizeStories "+$.colflow.redraw_in_progress;
	}
hideAll = function(){
	$("#main-submenu .link-container").removeClass("active");
	$(".homepage.about").removeClass("active");
	$(".homepage.essays").removeClass("active");
	$(".homepage.photos").removeClass("active");
	$(".homepage.poems").removeClass("active");
	$(".homepage.stories").removeClass("active");
	/* ie exception handling */
	$("#homepage-stories-menu").removeClass("active");
	
	$(".homepage.videos").removeClass("active");
	$(".homepage.homepage").removeClass("active");

	$(".content.essays").removeClass("active");
	$(".content.photos").removeClass("active");
	$(".content.poems").removeClass("active");
	$(".content.stories").removeClass("active");
	$(".content.videos").removeClass("active");
}
switchScheme = function(psWhichMode)
{
	try
	{
		/*  NB Brian entire function to jquery.bm_usr_interface.js */
		//  NB Brian todo - perhaps replace "title" attribute references with id.
		//  This change must by sync'd with loadFiles in utilities.
		$.bm_ui.template = psWhichMode;//STORIES PHOTOS POEMS ESSAYS VIDEOS ANIMATIONS

		// switch style sheets.
		//NB Brian to do 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.
		/*Note that I have added the Title attribute to each link ref so I can determine which sheets are loaded/enabled */
		if (psWhichMode == "DEFAULT")
		{
			$.bm_ui.colorscheme="WHITE";
			if (gbIE) {
				// in IE 8 disabling doesn't actually disable.
				// for now I'm removing the sheets entirely and then adding them as needed, which slows things down.
				$('link[@rel*=style][id]').each(function() 
				{
					//if (this.getAttribute('id') == "bm_stories_css") this.disabled = true;/* $(this).remove();*/	
					if (this.getAttribute('id') == "tab_css") this.disabled = true;	
					if (this.getAttribute('id') == "bio.css") this.disabled = true;
					if (this.getAttribute('id') == "black.css") this.disabled = true;
					if (this.getAttribute('id') == POETRY_SLIDESHOW_CSS_ID) $(this).remove();
					if (this.getAttribute('id') == "white.css") this.disabled = false;		
				});
				
			} else {
				//disable unused style sheets //
				$('link[@rel*=style][title]').each(function() 
				{
					if (this.getAttribute('title') == "bm_stories_css") this.disabled = true;	
					if (this.getAttribute('title') == "tab_css") this.disabled = true;	
					if (this.getAttribute('title') == "bio.css") this.disabled = true;
					if (this.getAttribute('title') == "black.css") this.disabled = true;
					if (this.getAttribute('title') == POETRY_SLIDESHOW_CSS_ID) this.disabled = true;
					if (this.getAttribute('title') == "white.css") this.disabled = false;		
				});
			}
			
		}

		if (psWhichMode == "BIO")
		{
			$.bm_ui.colorscheme="WHITE";
			//switch style sheet //
			$('link[@rel*=style][title]').each(function() 
			{
				if (this.getAttribute('title') == "bm_stories_css") this.disabled = true;	
				if (this.getAttribute('title') == "tab_css") this.disabled = true;	
				if (this.getAttribute('title') == "bio.css") this.disabled = false;
				if (this.getAttribute('title') == "black.css") this.disabled = true;
				if (this.getAttribute('id') == POETRY_SLIDESHOW_CSS_ID) this.disabled = true;
				if (this.getAttribute('title') == "white.css") this.disabled = true;	
			});
		}

		if (psWhichMode =="PHOTOS")
		{
			//switch style sheet //
			$('link[@rel*=style][title]').each(function() 
			{
				if (this.getAttribute('title') == "bm_stories_css") this.disabled = true;	
				if (this.getAttribute('title') == "tab_css") this.disabled = true;	
				if (this.getAttribute('title') == "bio_css") this.disabled = true;
				if (this.getAttribute('title') == "poems_css") this.disabled = true;
				//if (this.getAttribute('title') == PHOTOS_CSS_ID) this.disabled = false;
				
				$(".content.photos").addClass("active");
			});
			//document.getElementById("icon-dock2").style.display="block";
		}
		
		if (psWhichMode == "STORIES")
		{
			$.bm_ui.colorscheme="WHITE";
			//switch style sheet //
			$('link[@rel*=style][title]').each(function() 
			{
				if (this.getAttribute('title') == "bio.css") this.disabled = true;
				if (this.getAttribute('title') == "black.css") this.disabled = true;
				if (this.getAttribute('id') == POETRY_SLIDESHOW_CSS_ID) this.disabled = true;
				if (this.getAttribute('title') == "white.css") this.disabled = false;
				if (this.getAttribute('title') == "bm_stories_css") this.disabled = false;	
				if (this.getAttribute('title') == "tab_css") this.disabled = false;	
			});
			if (opera) {
				browserExceptions(1); //Opera issue. In utilities.js
			}
		}
		if (psWhichMode =="POEMS"){
			$.bm_ui.colorscheme="WHITE";
			//switch style sheet //
			$('link[@rel*=style][id]').each(function() 
			{
				if (this.getAttribute('title') == "bm_stories_css") this.disabled = true;	
				if (this.getAttribute('title') == "tab_css") this.disabled = true;	
				if (this.getAttribute('title') == "bio.css") this.disabled = true;
				if (this.getAttribute('title') == "black.css") this.disabled = true;
				if (this.getAttribute('title') == POETRY_SLIDESHOW_CSS_ID) this.disabled = false;
				if (this.getAttribute('title') == "white.css") this.disabled = false;		
			});
		}
		if (psWhichMode =="BLACK")
		{
			//alert("scheme black");
			$.bm_ui.colorscheme="BLACK";
			//switch style sheet //
			$('link[@rel*=style][title]').each(function() 
			{
				if (this.getAttribute('title') == "bm_stories_css") this.disabled = true;	
				if (this.getAttribute('title') == "tab_css") this.disabled = true;	
				if (this.getAttribute('title') == "bio.css") this.disabled = true;
				if (this.getAttribute('title') == "black.css") this.disabled = false;
				if (this.getAttribute('title') == POETRY_SLIDESHOW_CSS_ID) this.disabled = true;
				if (this.getAttribute('title') == "white.css") this.disabled = true;		
			});
			//document.getElementById("icon-dock2").style.display="block";
		}
	}
	catch(err)
	{
		errorHandler("bm_main.switchScheme",err);
	}
}
switchTabMain = function(psWhichTab)
{
	// only called by cs but should be called
	// once logged in need to change active page
	return;
	switch (psWhichTab) {
	case "preferences":
		//alert("stm - preferences");
		break;
	}
}
function contactSubmitKeypress(event){
	var iKey = getKeystroke(event);
	if (iKey == $.bm_ui.KEY_SPACE || iKey == $.bm_ui.KEY_ENTER) 
	{
		contactSubmit();
		return;
	}
}

contactSubmit = function(){
	//if (!$.bm_users.validateEmail("#contact-email-address",true,"#contact-message")) {document.getElementById("contact-email-address").focus();return;};
	//if (!$.bm_users.validateEmail("#contact-email-cc",false,"#contact-message")) {document.getElementById("contact-email-cc").focus();return;};
	var sEmail = $("#contact-email-address").attr("value");
	var sMessage = $("#contact-email-message").attr("value");
	var sSubject = $("#contact-email-subject").attr("value");
	var sCC= $("#contact-email-cc").attr("value");

	// Database version
	var sParams = "?user_key="+$.bm_users.user_key+"&message="+sMessage+"&subject="+sSubject+"&email="+sEmail+"&cc="+sCC;

	if ($.bm_users.show_query_params)winWrite("sparms contact message insert update "+$.bm_main.CONTACT_MESSAGE_INSERT_URL+sParams);
	httpRequest.open("GET", $.bm_main.CONTACT_MESSAGE_INSERT_URL+sParams, true);
	httpRequest.onreadystatechange = contactMessageInsert_HttpResponse;
	httpRequest.send(null)	

		/*
		//Email version
		$.post("php/mail.php", { from: sEmail,subject:sSubject,cc: sCC,message: sMessage},
		  function(data){
			//alert("processing return "+data);
			$.bm_users.messageShowContact(psMessageField,sResult,true);
		    //processXML(data);
		  });
		*/
}
contactMessageInsert_HttpResponse = function() {
		try
		{
			if (httpRequest.readyState == 4) 
			{
				var sResults = httpRequest.responseText;
				var e;
				messageShow("Your message has been delivered.","#contact-message",true);
			}
		} catch(err)
		{
			errorHandler("contactMessageInsert_HttpResponse",err);
		}
}


