// stage = the website that you're looking at
// frame = a frame is HTMl that is included into the page from external file
// scene = there are three scenes on the stage, scene 1 is off stage to the left, scene 2 is the one in the middle that you can see, scene 3 is the next scene off to the right
//         which frame is running is which scene is really important, as the scenes are slid around in the animation
// track = the container for the three scenes

// setup


//configObj = JSON.decode(configJson.responseJSON);
scenePrevFrame = false;
sceneThisFrame = false;
sceneNextFrame = false;
thisArea = 'home';
thisPage = 'home';
bgRevealStart = new Array();
tileGO = false;

// platform
	if (Browser.Platform.ipod) {
		platform = 'ipad'
	} else {
		platform = 'web'
	}

// cal the size of any object based on the width of the viewport	
function calcSize (itemX,itemY) {

	var output = new Array();

	// viewport size
	var bodySize = window.getSize();
	var viewPortX = bodySize.x;
	var viewPortY = bodySize.y;

	// calc the background height/width under normal conditions
	var sizeX = Math.round(itemX*bodyFactor);
	var sizeY = Math.round(sizeX*(itemY/itemX));
		
	output.sizeX = sizeX;
	output.sizeY = sizeY;
	
	return output;

}

// calc the size and position of an image
function calcBgSize (cssID,BDPos,BDOrigSizeX,BDOrigSizeY,switchHW) {

	if (!switchHW) {
		switchHW = 'auto';
	}

	var output = new Array();
	var mode;
	var sizeX;
	var sizeY;
	var posTop = 'auto';
	var posRight = 'auto';
	var posBottom = 'auto';
	var posLeft = 'auto';
	var offHoriz;
	var offVert;
	
	// viewport size
	var bodySize = window.getSize();
	var viewPortX = bodySize.x;
	var viewPortY = bodySize.y;

	if (viewPortX<viewPortY) {
	
		mode = 'VERTICAL';
		var m = 'v';
		
		// calc the background height/width under normal conditions
		var sizeY = Math.round(viewPortY*(BDPos.v.size/100));
		var sizeX = Math.round(sizeY*(BDOrigSizeX/BDOrigSizeY));
		
		// set the background horizontal offset 
		if (BDPos.v.left) {
			posLeft = Math.round(sizeY*(BDPos.v.left/100));
		} else if (BDPos.v.right) {
			posRight = Math.round(sizeY*(BDPos.v.right/100));
		}
		// set the background vertical offset 
		if (BDPos.v.top) {
			posTop = Math.round(sizeY*(BDPos.v.top/100));
		} else if (BDPos.v.bottom) {
			posBottom = Math.round(sizeY*(BDPos.v.bottom/100));
			
		}
		
	} else {
	
		mode = 'HORIZONTAL';
		var m = 'h';
		
		// calc the background height/width under normal conditions
		var sizeX = Math.round(viewPortX*(BDPos.h.size/100));
		var sizeY = Math.round(sizeX*(BDOrigSizeY/BDOrigSizeX));
		
		// set the background horizontal offset 
		if (BDPos.h.left) {
			var posLeft = Math.round(sizeY*(BDPos.h.left/100));
			offHoriz = posLeft;
		} else if (BDPos.h.right) {
			var posRight = Math.round(sizeY*(BDPos.h.right/100));
			offHoriz = posRight;
		}
		// set the background vertical offset 
		if (BDPos.h.top) {
			posTop = Math.round(sizeY*(BDPos.h.top/100));
			offVert = posTop;
		} else if (BDPos.h.bottom) {
			posBottom = Math.round(sizeY*(BDPos.h.bottom/100));
			offVert = posBottom;
			
		}
		
		// edge case where their could be letterboxing
		if ((sizeY+offVert)<viewPortY) {
			sizeY = Math.round(viewPortY*(BDPos.h.size/100));
			sizeX = Math.round(sizeY*(BDOrigSizeX/BDOrigSizeY));
			
			mode = 'HORIZONTAL (EDGE)';
		}
	
	}
	
	// debug
	// $('debug_mode').set('text',mode);
	// $('debug_imgactual').set('text',BDOrigSizeX + 'x' + BDOrigSizeY);
	// $('debug_imgdisplay').set('text',sizeX + ' x ' + sizeY + ' (' + posTop + ' ' + posRight + ' ' + posBottom + ' ' + posLeft + ')');
		
	// set width/height if 
	if (switchHW == 'h') {
		sizeX = Math.round(viewPortX*(BDPos[m].size/100));
		sizeY = Math.round(sizeX*(BDOrigSizeY/BDOrigSizeX));
	} else if (switchHW == 'v') {
		sizeY = Math.round(viewPortY*(BDPos[m].size/100));
		sizeX = Math.round(sizeY*(BDOrigSizeX/BDOrigSizeY));
	}
	// set height/width of background
	if ($(cssID + '_img')!=undefined) {
		$(cssID + '_img').setStyles({
			'width':sizeX,
			'height':sizeY
		})
	}
	
	// set offsets
	if ($(cssID)!=undefined) {
		$(cssID).setStyles({
			'position':'absolute',
			'top':posTop,
			'right':posRight,
			'bottom':posBottom,
			'left':posLeft
		})
	}
	
	
	output.mode = mode;
	output.sizeX = sizeX;
	output.sizeY = sizeY;
	output.posTop = posTop;
	output.posRight = posRight;
	output.posBottom = posBottom;
	output.posLeft = posLeft;
	output.offHoriz = offHoriz;
	output.offVert = offVert;
	
	return output;

}

// resize the track and the frames based on the browser viewport
function portScale () {

	// viewport size
	var bodySize = window.getSize();
	bodyWidth = bodySize.x;
	bodyHeight = bodySize.y;
	
	// scene size
	$$('.BD_scene').setStyle('width',bodyWidth);
	
	// font size
	bodyFactor =  Math.round((bodyWidth/768)*1000)/1000;
	var bodyFontSize = Math.round((bodyFactor * bodyFontBase)) + 'px';
	$$('body').setStyle('font-size',bodyFontSize);
	
	// debug
	// $('debug_fontfactor').set('text',bodyFactor);
	// $('debug_fontdisplay').set('text',bodyFontSize);
	// $('debug_fontbase').set('text',bodyFontBase);
	
	// debug
	// $('debug_size').set('text',bodyWidth + 'x' + bodyHeight);
	
	// set up track/frames
	$('BD_container').setStyle('width',bodyWidth);
	$('BD_container').setStyle('height',bodyHeight);
	$$('.BD_scene').setStyle('width',bodyWidth);
	$$('.BD_scene').setStyle('height',bodyHeight);
	$('BD_track').setStyle('height',bodyHeight);
	$('BD_track').setStyle('margin-left',(0-bodyWidth));
	
	// debug
	// $('debug_marg').set('text',$('BD_track').getStyle('margin-left'));
}


// allows the screen to be cleared of cruft to view background photos
function initBgReveal(cssId) {

	// cssId is the CSS id of the container
	
	var bgId = cssId+'_bg';
	if ($(cssId)==undefined) {
		return;
	}
	var faderDivs = $(cssId).getChildren('div');
	
	if (!$(bgId)) {
		return;
	}
	
	// get the alt tag of the background
	var bgTitle = $(bgId).getFirst('img').getProperty('alt');
	if (!bgTitle) {
		bgTitle = '';
	}
	var bgCredit = $(bgId).getFirst('img').getProperty('rel');
	if (bgCredit) {
		bgCredit = ' <small>' + bgCredit + '</small>';
	} else {
		bgCredit = '';
	}
	
	// get the initial opacity of the background:
	if (bgRevealStart[bgId]==undefined) {
		bgRevealStart[bgId] = $(bgId).getStyle('opacity');
	}

	// TOGGLE TO BACKGROUND
	if ($('BD_nav').getStyle('opacity')==1) {
	
		// kill any existing caption
		$('caption').setStyle('opacity',0);
		$('caption').set('text','');
	
		// fade the background in
		new Fx.Morph(bgId).start({ 'opacity':1 }).chain(function() {	
			// fade the navigation out
			new Fx.Morph($('BD_nav')).start({ 'opacity':0 }).chain(function() {					
				// hide the next/prev buttons
				// fade out all the relevent divs
				for(i=0;i<faderDivs.length;i++) {
				
					if ($(faderDivs[i]).getProperty('id')==bgId) {
						continue;
					}
					new Fx.Morph($(faderDivs[i])).start({ 'opacity':0 });
					
				}
				// fade the caption in
				$('caption').set('html',bgTitle + bgCredit );
				new Fx.Morph($('caption')).start({ 'opacity':1 });
				
				$('BD_nav2').setStyle('opacity',0);
				
				// set up the fade back to the foreground
				$(bgId).addEvent('click', function(event){
					
					// fade the caption out
					new Fx.Morph($('caption')).start({ 'opacity':0 }).chain(function() {	
						// fade the background out
						new Fx.Morph(bgId).start({ 'opacity':0.4 }).chain(function() {	
							// fade the navigation in
							new Fx.Morph($('BD_nav')).start({ 'opacity':1 }).chain(function() {					
								// show the next/prev buttons
								$('BD_nav2').setStyle('opacity',1);
								// make the scrolling area visible
								if ($(cssId+'_scrolling')!=undefined) {
									$(cssId+'_scrolling').setStyle('opacity',1);
								}
								// fade in all the relevent divs
								for(i=0;i<faderDivs.length;i++) {
							
									if ($(faderDivs[i]).getProperty('id')==bgId) {
										continue;
									}
								
									new Fx.Morph($(faderDivs[i])).start({ 'opacity':1 });
								
								}
								// fade in biog button
								$('BD_nav2_inner').getChildren('a').removeClass('on');
								$('BD_nav2_biog').addClass('on');
							});
						});
					});
				
				});
			});
		});
		
	} 
}

// quickly bring back the navigation if it's hidden
function navThaw() {
	
	// kill any captions
	$('caption').setStyle('opacity',0);
	$('caption').set('text','');
	
	// bring back nav2
	$('BD_nav2').setStyles({'visibility':'visible','opacity':1});
	
	// is the nav not visible?
	if ($('BD_nav').getStyle('opacity')<1) {
	
		// fade the navigation in
		new Fx.Morph($('BD_nav')).start({ 'opacity':1 }).chain(function() {					
			// show the next/prev buttons
			$('BD_prev').setStyle('opacity',1);
			$('BD_next').setStyle('opacity',1);
		});
	
	}
	
}



function initNav2 (actionsArray) {

	// the actionsArray is the array of key pairs that tell us whihcbuttons to activate

	// PICS
	if (actionsArray['pics']) {
		// reveal the button
		$('BD_nav2_pics').setStyle('display','block');
		// add the click
		$('BD_nav2_pics').addEvent('click', function(event){
			// stop the link off
			event.stop();
			// pop up gallery
			galleryPopLoad (this,actionsArray['pics']);
		})
	}
	// MOV
	if (actionsArray['mov']) {
		// reveal the button
		$('BD_nav2_mov').setStyle('display','block');
		// add the click
		$('BD_nav2_mov').addEvent('click', function(event){
			// stop the link off
			event.stop();
			// pop up gallery
			galleryPopLoad (this,actionsArray['mov']);
		})
	}
	// BIOG
	if (actionsArray['biog']) {
		// reveal the button
		$('BD_nav2_biog').setStyle('display','block');
		// add the click
		$('BD_nav2_biog').addEvent('click', function(event){
			// stop the link off
			event.stop();
			// pop up gallery
			biog_toggle(actionsArray['biog'])
		})
	}
	// STATS
	if (actionsArray['stats']) {
		// reveal the button
		$('BD_nav2_stats').setStyle('display','block');
		// add the click
		$('BD_nav2_stats').addEvent('click', function(event){
			// stop the link off
			event.stop();
			// pop up gallery
			biog_toggle(actionsArray['stats'])
		})
	}
	// FADE TO BACKGROUND
	if (!Browser.Engine.trident) {
		if (actionsArray['fade']) {
			// reveal the button
			$('BD_nav2_fade').setStyle('display','block');
			// add the click
			$('BD_nav2_fade').addEvent('click', function(event){
				// stop the link off
				event.stop();
				// start fade
				initBgReveal(actionsArray['fade'])
				// set "on"
				$('BD_nav2_inner').getChildren('a').removeClass('on');
			})
		}
	}
	// caption
	if (actionsArray['caption']) {
		$('BD_nav2_caption').set('text',actionsArray['caption']);
	}

}


function clearNav2 () {
	$('BD_nav2_caption').set('text','');
	$('BD_nav2').setStyles({'visibility':'visible','opacity':1});
	$('BD_nav2_pics').setStyle('display','none');
	$('BD_nav2_pics').removeEvents('click');
	$('BD_nav2_mov').setStyle('display','none');
	$('BD_nav2_mov').removeEvents('click');
	$('BD_nav2_biog').setStyle('display','none');
	$('BD_nav2_biog').removeEvents('click');
	$('BD_nav2_stats').setStyle('display','none');
	$('BD_nav2_stats').removeEvents('click');
	$('BD_nav2_fade').setStyle('display','none');
	$('BD_nav2_fade').removeEvents('click');
	$('BD_nav2_inner').getChildren('a').removeClass('on');
}


// set up the biog toggle
function biog_toggle(cssId) {

	var cssScroll = cssId+'_scrolling';
	var cssbg = cssId+'_bg';

	if ($(cssScroll)==undefined) {
		return;
	}

	var check = $(cssScroll).getStyle('visibility');
	if (check=='hidden') {
		new Fx.Morph($(cssbg),{'duration':1000}).start({ 'opacity':0.3 }).chain(function() {
			$(cssScroll).setStyles({'visibility':'visible'});
			new Fx.Morph($(cssScroll)).start({ 'opacity':1 });
		});
		$('BD_nav2_inner').getChildren('a').removeClass('on');
		$('BD_nav2_biog').addClass('on');
	} else {
		new Fx.Morph($(cssbg),{'duration':1000}).start({ 'opacity':1 }).chain(function() {
			new Fx.Morph($(cssScroll)).start({ 'opacity':0 }).chain(function () {
				$(cssScroll).setStyles({'visibility':'hidden','opacity':0});
			});
		});
		$('BD_nav2_inner').getChildren('a').removeClass('on');
	}

	
}



function tweak4ScrollBar(tweakIt) {
	var scrollbar = 17;
	if (Browser.Platform.mac) {
		scrollbar = 15;
	}
	if (tweakIt) {
		$('BD_nav').setStyles({'right':scrollbar});
		$('BD_nav2').setStyles({'right':scrollbar});
	} else {
		$('BD_nav').setStyles({'right':0});
		$('BD_nav2').setStyles({'right':0});
	}
}

// ONLOAD

window.addEvent('domready', function() {

	// set the scene
	$('BD_track').setStyles({'visibilty':'visible','opacity':0});
	$$('.BD_navsub').setStyles({'visibilty':'visible','opacity':0});
	$('BD_prev').setStyles({'opacity':0});
	$('BD_next').setStyles({'opacity':0});
	$('BD_nav_line_bot').setStyles({'opacity':0});
	$('BD_prev').addEvent('click', function() {pageBack();});
	$('BD_next').addEvent('click', function() {pageFoward();});
	$('BD_logo').setStyle('opacity',0);
	
	clearNav2();
	
	// default font size
	bodyFontBase = $$('body').getStyle('font-size');
	bodyFontBase = parseInt(bodyFontBase);
	
	// Pull in the json		
	var configJson = new Request.JSON({
		url: "frames.js",
		method: 'get',
		noCache: true,
		onSuccess: function(responseJSON,responseText) {
			configObj = responseJSON;
			loadStructure();
		},
		onFailure: function() {
		}
	}).send()
	
	// load the stage, frame structure and navigation
	function loadStructure () {
	
		var navlinks = $$('.BD_navlink');
		var configLength = configObj.frames.length;
		var counter = 1;
		// set up all the frames
		$each(configObj.frames, function(item) {
			//<div id="BD_scene1" class="BD_scene">111111111</div>
			var thisScene = new Element('div',{
				'id': 'BD_scene' + counter,
				'class': 'BD_scene',
				'html': counter
			});
			$('BD_track').grab(thisScene);
			counter++;
		})
		// set up the track
		$('BD_track').setStyle('width',(configLength*100) + '%');
		BDframes = $$('.BD_scene');
		
		// set up the navigation links
		$each(navlinks, function(item) {
		
			// pull out the id of the button
			var itemRel = item.getProperty('href');
			item.addEvent('click', function(){
				// use the button ID to find the frame
				for (i=0;i<configLength;i++) {
					if (configObj.frames[i].url==itemRel) {
						regFrame = i;
						break;
					}
				}
				framesLoad(regFrame);
				return false;
			});
		
		});
	
		// start up the frames
		if (newSlide) {
			// use the button ID to find the frame
			for (i=0;i<configLength;i++) {
				if (configObj.frames[i].url==newSlide) {
					regFrame = i;
					break;
				}
			}
		}
		framesLoad(regFrame);
	
		// run portscale onload()
		portScale();
	}
		
		
	// key actions
	window.addEvent('keydown', function(event){
		if (event.key == 'down') {pageFoward()};
		if (event.key == 'right') {pageFoward()};
		if (event.key == 'up') {pageBack()};
		if (event.key == 'left') {pageBack()};
	});
	
	// caption hide
	
	$('caption').addEvent('click', function(event){				
		// fade the caption out
		new Fx.Morph($('caption')).start({ 'opacity':0 })
	})
	
	// CLEAR DOWN THE FRAMES
		
	function framesClear (regFrame) {
	
		// run the pre off javascript for the main scene
		runJS(sceneThisFrame,'offpre');
		new Fx.Morph($('BD_track'),{ 'duration':500 }).start({ 'opacity':0 }).chain(function() {
			// run the post off javascript for the main scene
			runJS(sceneThisFrame,'offpost');
			
			scenePrevFrame = 0;
			sceneThisFrame = 0;
			sceneNextFrame = 0;
			
			// run the frame load again
			if (regFrame) {
				framesLoad (regFrame);
			} else {
				framesLoad (1);
			}
		});
	
	}

	
	// LOAD-UP THE FRAMES
	
	function framesLoad (regFrame) {
	
		BDframes = $$('.BD_scene');
	
		// defaults
		if (!regFrame) {
			regFrame = 1;
		}
		
		// if you want to jumpt o the frame that is already showing, do nothing
		if (sceneThisFrame>0 && regFrame==sceneThisFrame) {
			return false;
		// do a check to see if we should be going back or forward instead of jumping about
		} else if (sceneNextFrame>0 && regFrame==sceneNextFrame) {
			pageFoward(regFrame)
			return false;
		} else if (scenePrevFrame>0 && regFrame==scenePrevFrame) {
			pageBack(regFrame)
			return false;
		}
		
		// ok, we're jumping to a completely different place, check it's been cleared down, then re-run the load-up
		if (sceneThisFrame>0) {
			framesClear (regFrame);
			return false;
		}
		
		// check the nav is visible
		navThaw();
		
		// kill the nav2 buttons
		clearNav2();
		
		// set frames
		scenePrevFrame = regFrame-1;
		sceneThisFrame = regFrame;
		sceneNextFrame = regFrame+1;
				
		// load in the main frame visible scene (scene 2)
		new Request.HTML({  
			method: 'get',  
			url: configObj.frames[regFrame].url + '?ajax=1',  
			onSuccess: function() {
			
				// tell the scene what frame is loaded
				sceneThisFrame = regFrame;
				thisPage = configObj.frames[regFrame].url;
				thisArea = configObj.frames[regFrame].area;
				
				$('BD_track').setStyle('opacity',0);
				
				// run any pre javascript in the new frame
				runJS(regFrame,'onpre');
				// set up the nav
				navSetUp();
				
				// debug
				// $('debug_thisarea').set('text',thisArea);
				// $('debug_thispage').set('text',thisPage);
				// $('debug_scene2').set('text',sceneThisFrame);
				
				// load frame runtime js
				runJS(regFrame,'onpost');
		
				// jump to new place
				var bodySize = window.getSize();
				var bodyWidth = bodySize.x;
				var newMargin = (0-(regFrame*bodyWidth));
				$('BD_track').setStyle('margin-left',newMargin);
				
				// fade in the scenes track
				new Fx.Morph($('BD_track'),{ 'duration':500 }).start({ 'opacity':1 }).chain(function() {
				
					
					// check for the next frame in scene 3
					sceneNextFrame = regFrame+1;
					// if the frame we're looking for exists
					if (sceneNextFrame<configObj.frames.length) {
					
						// url
						nextURL = configObj.frames[sceneNextFrame].url + '?ajax=1';
						if (nextURL.length>0) {
						
							// pull next frame into scene 3
							new Request.HTML({  
								method: 'get',  
								url: nextURL,  
								onSuccess: function() {
								
									// run any pre javascript in the new frame
									runJS(sceneNextFrame,'onpre');	
									// fade in the next button
									new Fx.Morph($('BD_next')).start({ 'opacity':1 }).chain(function() {
									
										// check for the previous frame in scene 1
										scenePrevFrame = regFrame-1;
										// if the frame we're looking for exists
										if (scenePrevFrame>0) {
										
											// url
											prevURL = configObj.frames[scenePrevFrame].url + '?ajax=1';
											if (prevURL.length>0) {
											
												// pull previous frame into scene 1
												new Request.HTML({  
													method: 'get',  
													url: prevURL,  
													onSuccess: function() {
														// run any pre javascript in the new frame
														runJS(scenePrevFrame,'onpre');
														// fade in the prev button
														new Fx.Morph($('BD_prev')).start({ 'opacity':1 });
													},
													onFailure: function() {
														//console.log('cant find preframe: ' + prevFrame + ': ' + prevURL)
													},
													update: BDframes[scenePrevFrame]
												}).send();
												
											}
										} else {
										
											// kill the prev button
											new Fx.Morph($('BD_prev')).start({ 'opacity':0 });
						
										}
									
									});
								},
								onFailure: function() {
								},
								update: BDframes[sceneNextFrame]
							}).send();
							
						}
					} else {
					
						// kill the next button
						$('BD_next').setStyle( 'opacity',0 );
					
						// if the frame we're looking for exists
						if (scenePrevFrame>0) {
						
							// url
							prevURL = configObj.frames[scenePrevFrame].url + '?ajax=1';
							if (prevURL.length>0) {
							
								// pull previous frame into scene 1
								new Request.HTML({  
									method: 'get',  
									url: prevURL,  
									onSuccess: function() {
										// run any pre javascript in the new frame
										runJS(scenePrevFrame,'onpre');
										// fade in the prev button
										$('BD_prev').setStyle( 'opacity',1 );
									},
									onFailure: function() {
										//console.log('cant find preframe: ' + prevFrame + ': ' + prevURL)
									},
									update: BDframes[scenePrevFrame]
								}).send();
								
							}
						}
					}
				
				});
				
				
			},
			onFailure: function() {
			},
			update: BDframes[sceneThisFrame]
		}).send()
	
	}
	
	
	// PAGE BACK
	
	function pageBack() {
	
		BDframes = $$('.BD_scene');
	
		if (scenePrevFrame!=false) {
		
			// fade down the prev button
			new $('BD_prev').blur();
			$('BD_prev').setStyle('opacity',0);
			
			// find the pre close JS for the previous frame
			runJS(sceneThisFrame,'offpre');
			
			// check the nav is visible
			navThaw();
		
			// kill the nav2 buttons
			clearNav2();
			
			// kill any galleries
			galleryPopClose();
			
			// kill any pop-ups
			try {
				mindPopClear();
			} catch(err) {}
			
			// find the frames
			var currentMargin = $('BD_track').getStyle('margin-left').replace('px','');
			var newMargin = parseInt(currentMargin)+bodyWidth;
			
			//// $('debug_dif').set('text',BDtrackMidX + '-' + BDtrackStartX + '=' + BDtrackDiff + ' bwd');
			new Fx.Morph($('BD_track'),{ 'duration':500 }).start({ 'margin-left':newMargin }).chain(function(){
				// find the post close JS for the previous frame
				runJS(sceneThisFrame,'offpost');
				// load frame runtime js
				runJS(scenePrevFrame,'onpost');
				// find the prev frame to preload
				var prevFrame = scenePrevFrame-1;
				// if the frame we're looking for exists
				if (prevFrame>0) {
					// set up the scene locators
					sceneNextFrame--;
					sceneThisFrame--;
					scenePrevFrame--;
				
					// url
					prevURL = configObj.frames[scenePrevFrame].url + '?ajax=1';
					if (prevURL.length>0) {
					
						// pull next frame into scene 3
						new Request.HTML({  
							method: 'get',  
							url: prevURL,  
							onSuccess: function() {
									
								// fade up the prev button
								$('BD_prev').setStyle('opacity',1);
								// run any javascript in the new frame
								runJS(scenePrevFrame,'onpre');
								
							},
							onFailure: function() {
								
							},
							evalScripts: true,
							update: BDframes[scenePrevFrame]
						}).send();
						// fade up the next button
						$('BD_next').setStyle('opacity',1);
					}
				} else {
					// clear the end frame
					//BDframes[scenePrevFrame].set('html','');
					// set up the scene locators
					sceneNextFrame--;
					sceneThisFrame--;
					scenePrevFrame = false;
				}
				
				// set up the nav locators
				thisPage = configObj.frames[sceneThisFrame].url;
				thisArea = configObj.frames[sceneThisFrame].area;
				// set up the nav
				navSetUp();
				// debug
				// $('debug_thisarea').set('text',thisArea);
				// $('debug_thispage').set('text',thisPage);
				// $('debug_marg').set('text',$('BD_track').getStyle('margin-left'));
				// $('debug_scene2').set('text',sceneThisFrame);
			});
		}
		
		return false;
		
	}
	
	
	// PAGE FORWARD
	
	function pageFoward() {
	
		BDframes = $$('.BD_scene');
	
		if (sceneNextFrame!=false) {
		
			// fade down the next button
			new $('BD_next').blur();
			$('BD_next').setStyle('opacity',0);
			
			// find the pre close JS for the previous frame
			runJS(sceneThisFrame,'offpre');
			
			// check the nav is visible
			navThaw();
		
			// kill the nav2 buttons
			clearNav2();
			
			// kill any galleries
			galleryPopClose();
			
			// kill any pop-ups
			try {
				mindPopClear();
			} catch(err) {}
			
			// find the frames
			var currentMargin = $('BD_track').getStyle('margin-left').replace('px','');
			var newMargin = parseInt(currentMargin)-bodyWidth;
		
			//// $('debug_dif').set('text',BDtrackMidX + '-' + BDtrackStartX + '=' + BDtrackDiff + ' fwd');
			new Fx.Morph($('BD_track'),{ 'duration':500 }).start({ 'margin-left':newMargin }).chain(function(){
				// find the post close JS for the previous frame
				runJS(sceneThisFrame,'offpost');
				// load frame runtime js
				runJS(sceneNextFrame,'onpost');
				// find the next frame to preload
				var nextFrame = sceneNextFrame+1;
				// if the frame we're looking for exists
				if (nextFrame<=(configObj.frames.length-1)) {
				
					// set up the scene locators
					scenePrevFrame++;
					sceneThisFrame++;
					sceneNextFrame++;
					
					// url
					var nextURL = configObj.frames[sceneNextFrame].url + '?ajax=1';
					if (nextURL.length>0) {
					
						// pull next frame into scene 3
						new Request.HTML({  
							method: 'get',  
							url: nextURL,  
							onSuccess: function() {
									
								// fade up the next button
								$('BD_next').setStyle('opacity',1);
								// run any javascript in the new frame
								runJS(sceneNextFrame,'onpre');
								
							},
							onFailure: function() {
								
							},
							evalScripts: true,
							update: BDframes[sceneNextFrame]
						}).send();
						// fade up the prev button
						$('BD_prev').setStyle('opacity',1);
					}
				} else {
					// clear the end frame
					//BDframes[sceneNextFrame].set('html','');
					// set up the scene locators
					scenePrevFrame++;
					sceneThisFrame++;
					sceneNextFrame = false;
				}
				
				// set up the nav locators
				thisPage = configObj.frames[sceneThisFrame].url;
				thisArea = configObj.frames[sceneThisFrame].area;
				// set up the nav
				navSetUp();
				// debug
				// $('debug_thisarea').set('text',thisArea);
				// $('debug_thispage').set('text',thisPage);
				// $('debug_marg').set('text',$('BD_track').getStyle('margin-left'));
				// $('debug_scene2').set('text',sceneThisFrame);
		
			});
		}
		
		return false;
	}
	
	
	// SET-UP NAV
	
	function navSetUp () {
		
		// reset all the nav buttons
		$$('.BD_navlink').removeClass('on');
		
		var bodySize = window.getSize();
		var viewPortX = bodySize.x
		
		// TOP NAV
		// loop through all the opnav links
		var toplinks = $$('.BD_navlink_top');
		toplinksLength = toplinks.length;
		for(i=0;i<toplinksLength;i++) {
		
			// if this navlink is for this area
			if (toplinks[i].getProperty('rel')==thisArea) {
			
				// set the top nav on
				toplinks[i].addClass('on');
				
				// move the pointer
				var linkPos = toplinks[i].getPosition($('BD_nav_ul'));
				var linkSize = toplinks[i].getSize(toplinks[i]);
				var LinkLeft = linkPos.x + Math.round(linkSize.x/2)-20;
				new Fx.Morph($('BD_nav_line_top')).start({ 'left':LinkLeft });
					
				// blur the link (nasty highlight in windows)
				toplinks[i].blur();
				
			}
			
		
		}
		
		// SUBMENU NAV
		// test to see if the submenu exists
		if ($(thisArea + '_sub')!=undefined) {
			
			// test to see if the submenu is already up
			if ($(thisArea + '_sub').getStyle('opacity')<1) {
			
				// make all other menus invisible
				$$('.BD_navsub').setStyle('opacity',0);
				$$('.BD_navsub').setStyle('visibility','hidden');
				$('BD_nav_line_bot').setStyle('opacity',0);
				
				// make this submenu visible
				$(thisArea + '_sub').setStyle('visibility','visible');
				$('BD_nav_line_bot').setStyle('opacity',1);
				// fade it in
				new Fx.Morph($(thisArea + '_sub')).start({ 'opacity':1 });
			}
			
			// loop through all the BD_nav2 links
			var subMenuLinks = $(thisArea + '_sub').getChildren('li');
			subMenuLinksLength = subMenuLinks.length;
			for (i=0;i<subMenuLinksLength;i++) {
				
				// if this BD_nav2 link is for this page
				if (subMenuLinks[i].getFirst().getProperty('href')==thisPage) {
					// set the sub nav on
					subMenuLinks[i].getFirst().addClass('on');
				
					// move the pointer
					var linkPos = subMenuLinks[i].getPosition($('BD_nav_ul'));
					var linkSize = subMenuLinks[i].getSize(subMenuLinks[i]);
					var LinkLeft = linkPos.x + Math.round(linkSize.x/2)-20;
					new Fx.Morph($('BD_nav_line_bot')).start({ 'left':LinkLeft });
					
					// blur the link (nasty highlight in windows)
					subMenuLinks[i].getFirst().blur();
				}
			}
			
		} else {
		
			// make all menus invisible
			$$('.BD_navsub').setStyle('opacity',0);
			$$('.BD_navsub').setStyle('visibility','hidden');
			$('BD_nav_line_bot').setStyle('opacity',0);
		}
		
		
	
	}
	
	function runJS(regFrame,onoff) {
	
		if (!regFrame) {
			return false;
		}
	
		if (!onoff) {
			onoff = 'onpost';
		}
	
		// find the JS
		var jsUrl = configObj.frames[regFrame].url;
		jsUrl = jsUrl.replace('.php','_' + onoff + '.js');
		
		// pull next frame into scene 3
		new Request.HTML({  
			method: 'get',  
			url: jsUrl,
			onSuccess: function () {
				//alert('js found: ' + jsUrl)
				//console.log(jsUrl + ' (ok)')
			},
			onFailure: function () {
				//alert('js NOT found: ' + jsUrl)
				//console.log(jsUrl + ' (fail)')
			},
			evalScripts: true
			
		}).send();
	
	}

});
	
// ON RESIZE
window.addEvent('resize', function(){
	portScale();
	try {
		mindPopResize();
	} catch(err) {}
});
