/*
Semi-constants:
	Browser window: (browser resize adjusts these).
		winHeight
		winWidth

		
		Rules
			1) Only immediate (first) top, left, bottom, right boxes shown around home box.
			2) mousing over an item gets you next/previous adjacent item + all immediate children. (as well as trail to home).

*/

var focusLeft=0; //Used globally by animations to focus on or around a particular box
var focusTop=0;
var hoverBox = null;
var resizeTimer = null;
var focusEl="homeBox";
var mouseTrail = [];
var mouseTrailPointer = 0;
var menuHeight = $("#menu").height();

top.winHeight = $(window).height();
top.winWidth =  $(window).width();

top.containerLeft = 0;
top.containerRight = 0;
top.containerTop=0;
top.containerBottom=0;
top.containerMargin=103;

top.wasDragging=false;
top.moveAnimate=false;

/*
$("#boxSettingsBackground").bind("change",function() {
	$("#boxSettings").stop().animate({opacity:1});//Cuts off fade-out action.
})*/

$("#boxHelp,#boxSettings").hover(
	//Engineered so that mouseout inside a box (e.g. on a select pulldown input) doesn't trigger hiding of box
	function(){if ($(this).is(":visible")) $(this).stop().animate({opacity:1})},
	function(event){
		if(event.srcElement && event.srcElement.tagName=="SELECT") return;//Blocks IE from trigering fade out when inner form select chosen.
		$(this).animate({opacity:0},function(){$(this).hide()})
	}
);

$("#boxSettings input#snappy").bind("change",function(){
	top.moveAnimate=$(this).is(":checked");
})

$("#boxContact button").bind("click",function() {
	var myTarget=$("#boxContact select").val();
	var myMessage = $("#boxContact textarea").val();
	if (myTarget.length && myMessage.length) {
		$("#boxContact button span").text("SENDING ...");
		jit_send({type:"emailMessage",
			data:{
				to:myTarget,
				message:myMessage
			}
		},true,"lp/admin/");
	}
	else {jitclient_alert("Please select the addressee and type a message","Notice!");}

})

function jit_emailMessage(jit_event) {
	$("#boxContact button span").text("SENT!");
	setTimeout('$("#boxContact button span").text("Send");$("#boxContact textarea").val("");',4000);
}

function jit_emailMessage_error(jit_event) {
	jitclient_alert("There was a problem sending your message!  Try again!","Notice!");
	$("#boxContact button span").text("Problem!");
}

//$("#boxHelp,#boxSettings").bind("mouseout",function() {$(this).animate({opacity:0},function(){$(this).hide()})}

$("#helpLink").bind("click",function(){$("#boxHelp").show().css("opacity",1)});
$("#settingsLink").bind("click",function(){$("#boxSettings").show().css("opacity",1)});

$("button").wrapInner("<span></span>");//Enables fancy button styling

//Initially hide menu here.
$("#menu").css("opacity",0).hover(
	function(){$(this).stop().css("opacity",1)}, 
	function() {$(this).animate({opacity: 0})}
);

//If user changes window size, must gravitate current center.	
$(window).bind('resize', function() {
	top.winHeight = $(window).height();
	top.winWidth =  $(window).width();
	
	$('#'+focusEl).center();
	
	//top.centerTop = top.winHeight / 2;//+$(window).scrollTop();//homePosition.top;//
	//top.centerLeft = top.winWidth / 2;//+$(window).scrollLeft();//homePosition.left; //
	
	//if (resizeTimer) clearTimeout(resizeTimer);
	//resizeTimer = setTimeout("$(top.focusEl).myFocus()", 500);

});

jQuery.extend($.fn, {
	id : function (anId) {
	return this.each(function (anId) {
		//Setter: Set id to given anId//ONLY WORKS ON ONE ITEM
		//Should error if another el already has this id.
		if (anId) {$(this).attr("id",anId)}
		else 
			//DO NOTHING IF ITEM ALREADY HAS AN ID
			if (!$(this).attr("id").length) {
				var baseID = $.data(this);
				var difID = 0;
				var newID = document.getElementById("id_" + baseID); 
				if (newID) {//If this exists, then search for another.
					while (document.getElementById("id_" + (baseID + difID)))
						difID++;
					$(this).attr("id","id_" + (baseID + difID));//generates an ID.
				}
				else $(this).attr("id","id_" + baseID);
			 }
				
	});
  }
});


jQuery.fn.center = function () {
	var halfWidth = this.width()/2;
	var halfHeight=this.height()/2;
	var targetTop = ($(window).height() - this.height() ) / 2+$(window).scrollTop();
	var targetLeft = ($(window).width() - this.width() ) / 2+$(window).scrollLeft();
	top.focusTop = parseInt(targetTop)-0;
	top.focusLeft = parseInt(targetLeft)-0;
	top.focusEl = this.attr("id");
    return this;
}

$("#container").draggable({
	scroll:false, 
	//handle:".boxTitle,.homeBox",
	cancel:".box",
	distance:20,
	start:	function(){
		$("#menu").css("top","-100px");//Gets menu off screen
		$(this).css("background-image","url(images/grid.gif)").css("cursor","move");
	},
	drag: function(e){ 
	
	},
	stop:function(e,ui){
		$(this).css("background-image","").css("cursor","default");
		top.wasDragging=true;//A FLAG TO STOP click move action.
		//If velocity is significant enough, cause container to drag???
		//Handle indicates what to focus on in different ways:
	//	if (ui.helper.is(".boxTitle")) {$(ui.helper).trigger("click");}
	//	else {ui.helper.find(".boxTitle").trigger("click");}
		$('#'+top.focusEl).trigger("click");
		$("#crosshairs").css("width",$('#'+top.focusEl).width()+6+"px").css("height",$('#'+top.focusEl).height()+6+"px");	
	}
});

$("div.box").live("mouseover", function(e){
	if ($(this).css("opacity")==1) {//Since mouseover actions can happen on hidden divs, ensure user has this visible
		
		//SHOW ANY KIDS WHO ARE HIDDEN
		var kids = $(".box[parent="+$(this).attr("id")+"]");
		var first = kids.filter(":first");//alert(kids.length);
		if (first.length && first.css("opacity")!="1" && !first.is(":animated")) {
			//Turning on display
			kids.animate({opacity:1},1000);//Ahh! this animation is run completely, and in essence freezes any other motion animation for box until it is complete.
			kids.find("embed").css("visibility","visible");
		}
		if ($(this).data("next")) {$($(this).data("next")).filter(":not(:animated)").animate({opacity:1},1000);}
		if ($(this).data("previous")) {$($(this).data("previous")).filter(":not(:animated)").animate({opacity:1},1000);}
	};
	
	
});

//if mouse is at very boundary of screen, take this as a command to center on given box; otherwise lasso and title clicking is used.
//if (e.pageX < 2 || e.pageY < 2 || e.pageX >= top.winWidth-2 || e.pageY == top.winHeight-1) {mouseTrailReset();moveToBox($(this));return}
$("#borderLeft,#borderRight,#borderTop,#borderBottom").live("click",function(){
	mouseTrailReset();
	switch ($(this).attr("id")) {
		case "borderLeft": action = {left:"+="+top.winWidth/2};break;
		case "borderTop": action = {top:"+="+top.winHeight/2};break;
		case "borderRight": action = {left:"-="+top.winWidth/2};break;
		case "borderBottom": action = {top:"-="+top.winHeight/2};break;
	}
	$("#container").stop().animate(action);//	$("#container").animate({left:"+="+focusLeftDif,top:"+="+focusTopDif},1000);
});


$("div.box:not('.fixed')").live("mousemove",function(e){

	if (!$(this).is(":animated") && $(this).is(":visible") && $(this).css("opacity")>.3) {//

		if (top.hoverBox != $(this).attr("id")) {//Ensures lasoo calculations start as new div entered.
			mouseTrailReset();
			top.hoverBox = $(this).attr("id");
		}
		var thisPos = $(this).offset();

		//if mouse is at very boundary of screen, take this as a command to center on given box; otherwise lasso and title clicking is used.
		//if (e.pageX < 2 || e.pageY < 2 || e.pageX >= top.winWidth-2 || e.pageY == top.winHeight-1) {mouseTrailReset();moveToBox($(this));return}

		scaleX = parseInt((e.pageX-thisPos.left)/20);
		scaleY = parseInt((e.pageY-thisPos.top)/20);
		var key = scaleX+":"+scaleY;
		
	//	alert(mouseTrail[scaleX+":"+scaleY]!=undefined);
		if (top.mouseTrail[key]) {
			
			oldZ=top.mouseTrail[key];
						
			if ((top.mouseTrailPointer - oldZ) > 5) { // we've done a sizable loop.
				mouseTrailReset();
				if ($(this).is(".homeBox")) {$(this).trigger("click")}
				else $(this).find(".boxTitle").trigger("click");//MAKE SURE THIS IS THE RIGHT SPOT TO TRIGGER MOVE!
			}
		}
		else {
			top.mouseTrailPointer++;
			top.mouseTrail[key] = top.mouseTrailPointer; //start at 1 or logic fails in if(top.mouseTrail[key]) above
		}
	}
	return false;
}); 


$("#lassoTable,#lassoTable2").bind("mousemove",function(e){
	var lassoT = $(this);

	if (!$(this).is(":animated") && $(this).is(":visible") && $(this).css("opacity")>.3) {//

		var thisPos = $(this).offset();

		scaleX = parseInt((e.pageX-thisPos.left)/20);
		scaleY = parseInt((e.pageY-thisPos.top)/20);

		if (top.hoverBox != $(this).attr("id")) {//Ensures lasoo calculations start as new div entered.
			mouseTrailReset();
			lassoT.find("td").removeClass("selected").css("background-color","").text("");
			top.hoverBox = $(this).attr("id");
		}
				
		var key = scaleX+":"+scaleY;
		
		if (top.mouseTrail[key]) {
			oldItem=top.mouseTrail[key];
			//Here's the collision: oldItem.pointer was previous score for this cell, and now we have latest top.mouseTrailPointer score.
			if ((top.mouseTrailPointer - oldItem.pointer) > 5) { // we've done a sizable loop.
				mouseTrailReset();
				lassoT.find("td").removeClass("selected").css("background-color","").text("");//Clears out all styling done by path
			}
		}
		//BEGIN NEW MOUSE KEY MAP
		else {//This coordinate hasn't been found before so display it
			if (top.mouseTrailPointer==0) {//beginning of path
				top.mouseTrailBegin=key;
			}
			top.mouseTrailPointer++;
			var tailPointer = top.mouseTrailPointer;
			
			if ($(this).is("#lassoTable2")) {//Curtail beginning of trail
				
				var pathStart=top.mouseTrail[top.mouseTrailBegin];
				while (pathStart) {
					if (pathStart.pointer< tailPointer - 20) {
						toDelete = top.mouseTrailBegin;
						top.mouseTrailBegin=pathStart.next;
						pathStart.td.removeClass("selected").css("background-color","").text("");//only needed for demo visualization
						delete top.mouseTrail[toDelete];
						pathStart=top.mouseTrail[top.mouseTrailBegin];
					}
					else break;
				}
			}
			
			if (top.mouseTrailKey) {top.mouseTrail[top.mouseTrailKey].next=key}; //each key points to next key
			top.mouseTrailKey = key;
			var lassoTD = lassoGetTD(lassoT,e);//only needed for demo visualization
			top.mouseTrail[key] = {
				pointer:top.mouseTrailPointer,
				td:lassoTD
			}; //start at 1 or logic fails in if(top.mouseTrail[key]) above
			
			//DEMO VISUALIZATION: First lasso demonstration table shows only selected class
			if ($(this).is("#lassoTable")) {lassoTD.addClass("selected");}
			//2nd lasso demonstration table shows Z value and color to match
			else {lassoTD.css("background-color","rgb("+(90+tailPointer*4)+",128,128)").text(tailPointer);}

		}//END NEW MOUSE KEY
	}
	return false;
}); 

//MOUSE GESTURES: Lassoo motion detection
function mouseTrailReset() {
	top.mouseTrail=[];
	top.mouseTrailKey=null;
	top.mouseTrailPointer=0;
	return false;
}

function lassoGetTD(lassoT,e) {//FOR LASSO DEMO VISUALIZATION ONLY
	var lasso=lassoT.offset();
	var lassoX=parseInt(e.pageX-lasso.left);
	var lassoY=parseInt(e.pageY-lasso.top);
	var lassoXS = parseInt(lassoX/20);
	var lassoYS = parseInt(lassoY/20);
	$("#lassoTableTitle").text("Mouse Coordinates: ("+ lassoX +" , "+lassoY + ") scaled to: (" + lassoXS + " , " + lassoYS + ")");
	return lassoT.find("tbody tr:eq("+lassoYS+") td:eq("+lassoXS+")");
}


/*
$("#boxHelp,#boxSettings").hover(
	//Engineered so that mouseout inside a box (e.g. on a select pulldown input) doesn't trigger hiding of box
	function(){if ($(this).is(":visible")) $(this).stop().animate({opacity:1})},
	function(){$(this).animate({opacity:0},function(){$(this).hide()})}
);
*/


//Menu appears & dissapears
$("div.box").hover(
	function(){
		if ($(this).css("opacity")>.3) {// >.3            && !$(this).is(":animated")
//		if ($(this).is(":visible")) {
	//		$(this).stop();
//		if (1==1) {
					
			showBoxUp($(this));
			//If some text/html contents exist, show them
			var content = $(this).children(".boxContent");
			if (content.length && content.html().length>4 && content.css("opacity")<.6) content.stop().show().animate({"opacity":.9},500);
			var contentLeft = $(this).children(".boxContentLeft");
			if (contentLeft.hasClass("hover")) {contentLeft.stop().show().animate({"opacity":.9},500);};

			// showMenu($(this)); //Only if logged in
		}
	}, 
	function() {
		$(this).find(">.boxTitle >.boxUp").hide();//Get rid of previous/parent nav arrow.
		var content = $(this).children(".boxContent");
		var contentLeft = $(this).children(".boxContentLeft");
		if ($(this).is(".depth1") || content.hasClass("hover")) {
			content.stop().animate({"opacity":"0"},2000);//,function(el){$(el).hide()}
		}
		if (contentLeft.hasClass("hover")) {
			contentLeft.stop().animate({"opacity":"0"},2000);//,function(el){$(el).hide()}
		}
		$("#menu:visible").stop().animate({opacity: 0});//do only if there is a visible menu?!
//		if ($(this).is(".depth1")) {$(this).find(".boxContent").animate({"opacity":0},1500)}
	}
);


function showMenu(item) {
	var position=$(item).position();
//		alert(position.left + ":" + top.containerLeft + ":" + $(this).width() + ":" + $(this).offsetLeft);
	//alert(position.top + ":" + top.containerTop + ":");
	var cont = $("#container").position();
	$("#menu").css("left",(position.left+$(item).width()-25)+"px")//position.left+ //cont.left
		.css("top",(position.top - menuHeight-5)+"px")
		.stop().animate({opacity: 1});

				
}
//NOTE: ANY DIV WHICH ISN'T SECTION OR HOME PAGE NEEDS Z-index=-1 or else it will get clicked on here, superceeding home page. Done via stylesheet
//Moves focus to given item by simple left+180;top:+180 etc depending on relative position of clicked on box re center screen
//$("div.box").bind("click",function() {
//	moveToBox($(this));
//});

$("div.homeBox").bind("click",function() {moveToBox($(this))});

//Editing function.
$("div.boxTitle,div.boxContent").live("dblclick",function() {});

function moveToBox(newFocus) {
	$("#menu").css("top","-100px");//Gets menu off screen
	
	
	//If new box is partly off of screen, center it
	var focusOffset = $(newFocus).offset();
	if (focusOffset.left < 15 || focusOffset.top < 15 || focusOffset.left + newFocus.width() > top.winWidth-15 || focusOffset.top + newFocus.height() > top.winHeight-15 ) {centerBox(newFocus)}
	
	var focusPos = $('#'+top.focusEl).position();
	focusLeftDif = focusPos.left + $('#'+top.focusEl).width()/2 - (newFocus.position().left + newFocus.width()/2);
	focusTopDif = focusPos.top + $('#'+top.focusEl).height()/2  - (newFocus.position().top + newFocus.height()/2);;
	top.focusEl = newFocus.attr("id");


	if (top.wasDragging==true) {
		top.wasDragging=false;
		return
	}
		
	doCrosshairs();
	
	//Ensure kids are shown
	
	//Shift container appropriately
	if (top.moveAnimate==true) {//User has animation still on
		$("#container").animate({left:"+="+focusLeftDif,top:"+="+focusTopDif},1000);
	}
	else {//Just jump right to place		

		//alert((focusLeftDif+"px") + ":" + (focusTopDif+"px"));
		//IE Running into problems doing relative positioning of container so...
		var contPos = $("#container").offset();
		$("#container").css("left",(focusLeftDif+contPos.left)+"px").css("top",(focusTopDif+contPos.top)+"px");	

	}

	var myParent = newFocus;
	var myCrumbs = newFocus.find(".sectionTitle,.boxTitle").text();
	if (myCrumbs.length>0) myCrumbs = " &gt; " +  '<span class="navLink" FOR="'+ newFocus.attr("id")  +'">' + myCrumbs + '</span>';

	while (myParent && myParent.attr("parent")) {
		var parentID = myParent.attr("parent");
		var myParent = $("#" + parentID);
		if (myParent && myParent.length>0 && !myParent.is("#homeBox")) {
			myCrumbs = " &gt; " + '<span class="navLink" FOR="'+ parentID +'">' + myParent.find(".sectionTitle,.boxTitle").text() + '</span>' + myCrumbs;
		}
	}
	//IE WANTS DYNAMICALLY GENERATED "FOR" TO BE IN CAPS?!?!?!
	$("#crumbLink").html('<span class="navLink" FOR="homeBox">Home</span> '+ myCrumbs);
	
	
	//SHOW IMMEDIATE KIDS
	var kids = $(".box[parent="+newFocus.attr("id")+"]");
	//kids.css("opacity",1);
	
	if (kids.length && kids.filter(":first").css("opacity")!="1") {
		kids.animate({opacity:1},300);//Ahh! this animation is run completely, and in essence freezes any other motion animation for box until it is complete.
	}
}

function doCrosshairs() {
	//If a box doesn't focus correctly that can be because there are two ID's existing
	var newFocus = $("#"+top.focusEl);
	if (newFocus.length>1) alert("Two or more boxes have the same ID: " + top.focusEl);//Doesn't detect in firefox.only 1st id recognized
	/*
	$("#crosshairs")
		.css("left",(newFocus.position().left-1)+"px")
		.css("top",(newFocus.position().top-1)+"px")
		.css("width",newFocus.width()+4+"px")
		.css("height",newFocus.height()+4+"px");
	*/
	$("#crosshairs").animate(
		{left:newFocus.position().left-4,
		top:newFocus.position().top-4,
		width:newFocus.width()+6,
		height:newFocus.height()+6	
		},300);
}

/*
$("span.boxLink").bind("click",function() {
	//Ensure all this box's kids are shown
	var kids = $("body .box[parent="+$(this).parents("div.box:first").attr("id")+"]");
	if (kids.length && kids.filter(":first").css("opacity")!="1") {
		kids.animate({opacity:1},300);//Ahh! this animation is run completely, and in essence freezes any other motion animation for box until it is complete.
	}
	
	$("#"+$(this).attr("link")).trigger("click");
	return false;//Prevents bubbling
})
*/

$(".navLink").live("click",function(){
	var reference = $(this).attr("FOR");//IE WANTS CAPS ON DYNAMICALLY GENERATED FOR refs.
	//alert(reference);
	if (reference) {
		var target = $('#'+reference);
		centerBox(target);
		moveToBox(target);
	}
	return false;
});

//Makes all container area boxes visible:
$("#viewLink").bind("click",function(){
	$('.box').animate({opacity:1},1000).find("embed").css("visibility","visible");
});

function init() {
	//1) Calculate box layout, and calculate container width & height
	doLayout($(".homeBox"));//Calculates positions of everything relative to Home.
	//$('#container').css("background-image","url(images/grid.gif)"); 
	
	//$(".sectionTitle").css("opacity",.7);//for all browsers //PROBLEM THIS ACTUALLY PREVENTS CLICK ON HOVER
		
//	$("#crosshairs").animate({opacity: 1});//Hide border around focused item to start.
	  
	centerBox();

	$(".box:not(.homeBox,#boxHelp,#boxSettings)").css("opacity","0");	//hides all but home and section
	$(".box,#crosshairs").css("visibility","visible");
		  
	  //NOW, if URL mentions local anchor : "#blabla", and #blabla exists, reveal it and its sibling / parent path to home.
	var myAnchor = document.location.href.indexOf("#");
	if (myAnchor!=-1) {
//		$("html").scrollTo(0,0);
		$("body").scrollTop(0);
//		document.body.scrollTop=0;
		//window.scrollTo(0,1000);
		$(".depth1.firstBox").show();//fast
		myAnchor = document.location.href.split("#").pop();
		var myEl = $("#" + myAnchor);
		if (myEl.is(".box")) {
			moveToBox(myEl);
			myEl.animate({opacity: 1},300);//NEED TO TAKE CARE OF PARENT TRAIL
		}
	}
	else {
		
		/*
		//Remember current positions for all section items
		$(".depth1.firstBox").each(function() {
			//prePos.push($(this).position);
			$(this).css("left",top.focusLeft+"px");
			$(this).css("top",top.focusTop+"px");
		});
		*/
		//alert(  $('.depth1.boxRight.firstBox').html());

		//$('.depth1.firstBox').animate({opacity: 1},2000);
		
		
		  $('.depth1.boxTop.firstBox').each( function() {
				$(this).animate({opacity: 1});//,  top:  "-=" + ($(this).height()+20)+"px"}, 1500);
//				$(this).css({opacity: 1}).show("slide", { direction: "down" }, 1500);
			});
	 
		  $('.depth1.boxRight.firstBox').each( function() {
		  		$(this).animate({opacity: 1},1200);//,left: "-=" + ($(this).width()+20)+"px"}, 1200);
//				$(this).css({opacity: 1}).show("slide", { direction: "right" }, 1200);
	 		});

		    $('.depth1.boxBottom.firstBox').each( function() {
				$(this).animate({opacity: 1},2500);//, top: "+=" + ($(this).height()+20)+"px"}, 1700);
//				$(this).css({opacity: 1}).show("slide", { direction: "up" }, 1700);
			});

			
		  $('.depth1.boxLeft.firstBox').each( function() {
		  		$(this).animate({opacity: 1},4000);//,left:  "+=" + ($(this).width()+20)+"px"}, 800);
//				$(this).css({opacity: 1}).show("slide", { direction: "left" }, 800);
			});
			

	}	
	var topDisp = (188/2-20);
	var leftDisp = (208/2-20);
	$("#barAcross").css("top",top.focusTop+topDisp+"px").css("opacity",0.3);
	$("#barDown").css("left",top.focusLeft+leftDisp+"px").css("opacity",0.3);
	
	$(".depth1 > .boxContent").css("opacity",0);	  
}

function centerBox(box) {
	if (!box) box = $('#homeBox');
	box.center(); //Gets coordinates of center screen - 1/2 box width, height.
	var homePos=box.position();
	$("#container").css("left","+"+top.focusLeft-homePos.left+"px").css("top","+"+top.focusTop-homePos.top+"px");
	doCrosshairs();
	$("#crosshairs").animate({opacity: 1},100);
	box.animate({opacity: 1}, 1000, function() {});//show home box
	var homePos=box.position();
	top.focusTop = homePos.top;
	top.focusLeft = homePos.left;

}
/* As we calculate position of all boxes, we also keep track of how big the drawing board needs to be that shows all these pieces (top.containerLeft / Right / Top / Bottom / Width / Height).
*/
function doLayout(homeNodes) {

	//Cycle through each section, and find its kids, and set their positions.
	$(homeNodes).each(function(i,item) {

		var homePos = $(item).position();
		//top to bottom order of kids in dom is order they are picked up and processed.
		var kids = $("body .box[parent=" + $(item).attr("id") + "]");
		var depth = 1;
		kids.each(function(i2,item2) {
			doLayout2(i2,item2,kids,item,1);//First kid so provide default
		});

	});
	//Shift items so they center inside grid
	$("#container .box").each(function(i,item){
		var pos = $(this).position();
		$(this).css("top",(pos.top -top.containerTop+ top.containerMargin)+"px");
		$(this).css("left",(pos.left -top.containerLeft +top.containerMargin)+ "px");		
	})
	
	$("#container").width(top.containerWidth+2*top.containerMargin).height(top.containerHeight+2*top.containerMargin);

	//NOW SHOW NAV Arrows for each box
	
	$("div.box:not(.homeBox)").each(function() {//.sectionBox
	
		var thisParent = $(this).attr("parent");
		if (thisParent && thisParent.length)//text of id
			thisParent = $("#"+thisParent);
		else return; //thisParent = $("#homeBox");
		if (thisParent.length==0) {
			alert('Box "' + $(this).attr("id") + '" mentions parent "' + thisParent + '" but no such parent exists!');
			return;
		}
		var parentPos = thisParent.position();
		var thisPos = $(this).position();
		var vert = (parentPos.top - thisPos.top);
		var horiz = (parentPos.left - thisPos.left);
		if (vert==0) {
			if (horiz < 0) icon = "iconLeft";
			else icon = "iconRight";
		}
		else {
			if (vert < 0) icon="iconUp";
			else icon="iconDown";
		}

		var myBox = $(this);
		var goTo = myBox.data("previous");		//First try to navigate to previous sibling.
		if (goTo) goTo = $(goTo).attr("id");
		else goTo = myBox.attr("parent");
		if (goTo && goTo.length>0)
			$(this).children(".boxTitle").prepend('<div class="boxUp '+icon+'" target="' + goTo + '"></div>');
		
	});

	//Navigate to previous sibling OR to parent
	$(".boxUp").bind("click",doBoxUp);

}

function showBoxUp(item) {
	var myTarget = item.find(">.boxTitle >.boxUp").attr("target");
	if (myTarget && myTarget != focusEl) item.find(">.boxTitle >.boxUp").show();
}

function doBoxUp(){
	var target = $(this).attr("target");
	if (target == "homeBox") {$("#homeBox").trigger("click");}
	else {$("#"+target).children(".boxTitle").trigger("click");}

	//hide this item and all its siblings and sub-items
	//var myID = $(this).parent().attr("id");
	//hideAllKids(myParent);


	return false;//Otherwise event triggered on new focus area too?
}		

//This gets carriage returns into hover help info
$("#boxLeader").attr("alt", "Click on a box title to focus on that item. \n\n Drag a box by its title to reposition the focus area.");

	
$("#boxSettingsBackground").bind("change",function(event) {
	var selection = $(this).val();

	$("body").css("background-image","url(images/"+selection+")");
	//Adjustment for one background that needs a bit of a margin
	if (selection=="background4.gif") $("body").css("background-position","center 50px");
	else $("body").css("background-position","top center");
	$("body").css("background-color", (selection=="spacer.gif") ? "white" :"#777");
})



//ADD AWARENESS OF SIBLINGS, so as sibling is positioned, prev sibling gets attr("next/previous",$(this).attr("id"));




function doLayout2(i2,item2,kids,aparent,depth) {
	if (i2==0) {
		previous = aparent;//SWITCH HORIZ/VERT HERE
	}
	else previous = $(kids[i2-1]);
	//Ensure that each kid has a left/right/top/bottom direction.
	if (!$(item2).attr("layout")) {
		//Calculate which box it should be; by default its .rightBox
		if (previous==aparent) {	
			$(item2).attr("layout","right");
		}//First kid so provide default
		else {$(item2).attr("layout",previous.attr("layout"))}//Otherwise inherit from previous sibling
	}
	//A change in direction is taken from parent, not previous sibling.  NOTE comparison will fail if prev doesn't have attr=""... e.g. homeBox.
	else if (layout != $(previous).attr("layout")) {
		previous = aparent;
		if (depth==1) $(item2).addClass("firstBox");
	}
			
	//Now process each kid according to direction above.  (All siblings usually line up in same direction.).
	$(item2).addClass($(item2).attr("layout")+"Box").addClass("depth"+depth);

	var layout = $(item2).attr("layout");

	var prevPosition = $(previous).position();

	var boxOffset = 20;
//	if (depth == 1) {boxOffset = 50;}
	if ($(aparent).is("#homeBox")) {$(item2).addClass("sectionBox");}
	if ($(aparent).is(".sectionBox")) {boxOffset = 50;}
	
	$(item2).id();//assigns an id if it doesn't have one.//usually only furthest descendants in this case.
	//Decide which way kids will be oriented - up, down, left, right.  Depends on how newFocus is oriented with respect to home page box.

	topOffset = prevPosition.top;
	leftOffset = prevPosition.left;
	if (layout.indexOf("top") !=-1|| layout.indexOf("bottom")!=-1) {//Section is above or below
		var prevWidth = $(previous).width();
		if (prevWidth <= 200) {leftOffset = prevPosition.left+$(previous).width()/2-$(item2).width()/2;}
		else {leftOffset = prevPosition.left;}//top/bottom change box inherit's parent's horizontal position.
		if (layout =="top")  {
			topOffset = prevPosition.top - $(item2).height()-boxOffset;
			$(item2).addClass("boxTop");
		}
		else  {
			topOffset = prevPosition.top + $(previous).height()+boxOffset;//boxBottom
			$(item2).addClass("boxBottom");
		}
	}
	if (layout.indexOf("left") !=-1|| layout.indexOf("right")!=-1) {//section is to left or right.
			if (layout=="left") {
				leftOffset = prevPosition.left - $(item2).width()-boxOffset;
				$(item2).addClass("boxRight");
			}
			else {
				leftOffset = prevPosition.left + $(previous).width()+boxOffset;
				$(item2).addClass("boxLeft");
			}
	}
	$(item2).css("top",topOffset +"px");
	$(item2).css("left", leftOffset +"px");


	//Enable siblings to know each other's order.
	$(item2).data("previous",previous);
	$(previous).data("next",item2);
	
				
	if (topOffset < top.containerTop) {top.containerTop = topOffset}
	if (topOffset+$(item2).height() > top.containerBottom) {top.containerBottom = topOffset+$(item2).height()}	
	if (leftOffset < top.containerLeft) {top.containerLeft = leftOffset}
	if (leftOffset+$(item2).width() > top.containerRight) {top.containerRight = leftOffset+$(item2).width()}					
	
	top.containerWidth = top.containerRight - top.containerLeft;
	top.containerHeight = top.containerBottom - top.containerTop;		

	
	//Now process the kids'' kids
	var kids3=$("body .box[parent=" + $(item2).attr("id") + "]");
	kids3.each(function(i3,item3) {
		doLayout2(i3,item3,kids3,item2,depth+1);//First kid so provide default
	});


}

function hideAllKids(myID) {
	var kids = $(".box[parent="+myID+"]");
	kids.each (function() {
			$(this).animate({opacity:0},1000);//Ahh! this animation is run completely, and in essence freezes any other motion animation for box until it is complete.
			if ($(this).attr("id")) hideAllKids($(this).attr("id"));
	});
}



/*
//Centers screen on current top.focusEl
jQuery.fn.myFocus = function () {

	top.centerTop = top.winHeight / 2+$(window).scrollTop();//homePosition.top;//
	top.centerLeft = top.winWidth / 2+$(window).scrollLeft();//homePosition.left; //
	
	if ($(".box:animated").length==0) {//Strangely window resize is called on window load.
		var halfWidth = this.width()/2;
		var halfHeight=this.height()/2;
		var targetTop = ($(window).height() - this.height() ) / 2+$(window).scrollTop();
		var targetLeft = ($(window).width() - this.width() ) / 2+$(window).scrollLeft();
		top.focusTop = parseInt(targetTop)-0;
		top.focusLeft = parseInt(targetLeft)-0;
	
		focusLeftDif = top.focusLeft - $(this).position().left;
		focusTopDif = top.focusTop - $(this).position().top;
	
		$(".box").stop().animate({left:"+="+focusLeftDif,top:"+="+focusTopDif},500);
		
		$("#crosshairs").animate({left:"+="+focusLeftDif,top:"+="+focusTopDif},500); //css("left",top.focusLeft-1+"px").css("top",top.focusTop-1+"px")
	
	}
    return this;
}	
*/




//Ensures all local anchors on page will trigger moves to appropriate box:
$("a[href^=#]").bind("click",function() {
	var myref = $(this).attr("href");
	var myEl = $(myref);
	if (myEl.is(".box")) {
		moveToBox(myEl);
		myEl.animate({opacity: 1},300);//NEED TO TAKE CARE OF PARENT TRAIL
		
		
		
		
		
		
		
		return false; //Critical, or else browser continues with anchor repositioning (using #ID=xyz rather than just <a name="xyz"></a> as target.)
	};
})
/*
$("a").live("click",function(event) {
  event.stopPropagation();
  event.cancelBubble=true;
});
*/

//Fixed items can't be moved
//$("div.boxTitle").live("click",function() {
//	if ($(this).parent().is(":not(.fixed)")) {
//		var target=$(this).parent();

$("div.box").live("click",function() {
	if ($(this).is(":not(.fixed)")) {var target=$(this);moveToBox(target)}
});

init();

