//global vars
var scalefactor = .2;
var boxwidth;
var boxheight;
var boxleft;
var boxtop;
var vpleft;
var vptop;
var vpwidth = 100000;
var vpheight = 20000;
var xstart;
var ystart;
var totaldx;
var totaldy;
var totaldh;
var totalframes = 6;
var framedx;
var framedy;
var framedh;
var framenumber;
var centermap;
var initialwidth;
var dragx;       //starting mouse coordinates for drag
var dragy;
var currentCategory;
var currentSubCategory;
var page;
var floType;
var topMapID;
var firstLoad = true;
var animating = false;
var frameInterval;
var frame = false;
var level = 2;
var removeSize;
var startDragX;
var startDragY;
var currentMouseX;
var leftMapID;
var rightMapID;
var topMapID;
var bottomMapID;
var allowDrag = false;
var dragInterval;
var firstMove = false;
var dragMomentum = 0;
var totalDrag = 0;
var pageBlockLength;
var currentPageBlockIndex = 0;
var browserVersion;
var selectedMapID;
var controlDisplayed = false;
var remoteSelectedX;
var animateInterval;
var controlMode = 'none';
var playerWidth;
var playerHeight;
var mapStartX = 0;
var vpStartX;


function docReady(){
	if (navigator.appVersion.match('Safari')) browserVersion = 'safari';
	else if (navigator.appVersion.match('MSIE')) browserVersion = 'msie';
	else browserVersion = 'firefox';
	if (browserVersion == 'safari') removeSize = 40000;
	else removeSize = 300000;
	
	if (!$('#fbcss').length > 0) {
		$(window).bind('resize', resizeBrowserWindow);
	}	
}

function onInit() {
	$('#thebox').bind('mouseup', doNothing);
	document.onselectstart = function() {return true;} // ie
	document.onmousedown = function() {return true;} // mozilla
	boxleft = parseFloat($('#thebox').css('left').split('px')[0]);
	boxtop = parseFloat($('#thebox').css('top').split('px')[0]);
	level = 2;
	mapStartX = 0;
	$('#viewport').empty();
	initializeAdjacentMaps();
	$('#thebox').children('.scrollArrow').hide();
	$('#statsPageBody').remove();
}

function startRemoteMode() {
	$('#remoteModeButton').blur();
	if ($('#remoteModeButton').attr('class') == 'remoteModeButtonNoSelect'){
		clearInterval(dragInterval);
		$('#remoteModeButton').attr('class', 'remoteModeButtonSelect');
		$(document).keyup(keyStroke);
		$('#remoteControlBox').show();
		selectMap($('#pb_0').children('.map')[0]);
	}
	else if ($('#remoteModeButton').attr('class') == 'remoteModeButtonSelect') {
		$('#remoteModeButton').attr('class', 'remoteModeButtonNoSelect');
		$(document).unbind('keyup');
		$('#remoteControlBox').hide();
		$('#glows_'+selectedMapID).hide();
		$('#shadows_'+selectedMapID).show();
		$('#'+currentSelection).css('border', 'none');
	}
}

function keyStroke(event) {
	
	if (selectedMapID!=null) {
		selectedMap = $('#'+selectedMapID);
	}
	
	var remoteControlBox = $('#remoteControlBox');
	
	if($(remoteControlBox).attr('class') == 'remoteMapControlBox') {
		if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
			var offset = $(selectedMap).offset();
			var mapLeft = offset.left - boxleft;
			var mapTop = offset.top - boxtop; 
			var mapHeight =  $(selectedMap).attr('offsetHeight');
			var mapWidth = $(selectedMap).attr('offsetWidth');
			if(event.keyCode == 37) {
				searchX = mapLeft - .5 * mapWidth;
				searchY = mapTop + .5 * mapHeight;
			}
			else if (event.keyCode == 38) {
				searchX = mapLeft + .5 * mapWidth;
				searchY = mapTop - 1.5 * mapHeight;
			}
			else if (event.keyCode == 39) {
				searchX = mapLeft + 1.5 * mapWidth;
				searchY = mapTop + .5 * mapHeight;
			}
			else if (event.keyCode == 40) {
				searchX = mapLeft + .5 * mapWidth;
				searchY = mapTop + 2.5 * mapHeight;
			}
			searchCoordinatesAndSize(mapWidth, mapHeight, searchX, searchY);
		}
		else if (event.keyCode == 13) {
			if(parseInt($(selectedMap).css('z-index')) == level) {
				if ($(selectedMap).attr('name') == 'page') onNodeClick($(selectedMap).attr('id'));
				else if ($(selectedMap).attr('name') == 'content') {
					if (floType == 'floCreate') addToRecent = 'false';
					else addToRecent = 'true';
					directPlayVideo($(selectedMap).attr('id'), addToRecent);
				}	
			}
			else if (parseInt($(selectedMap).css('z-index')) < level) {
				selectMap($(selectedMap).children('.map')[0]);
			}
		}
		else if (event.keyCode == 32) {
			$('#remoteControlBox').attr('class', 'remoteMapMenuBox');
		}
	}
	else if($(remoteControlBox).attr('class') == 'remoteMapMenuBox') {
		if (event.keyCode == 32) {
			
			if(parseInt($(selectedMap).css('z-index'))==level) {
				if(level!=2) {
					selectMap($(selectedMap).parent());
				}
				
			}
			else if (parseInt($(selectedMap).css('z-index'))<level) {
				goBack($(selectedMap).attr('id'));
			}
			$('#remoteControlBox').attr('class', 'remoteMapControlBox');
		}
		else if (event.keyCode == 13) {
			$('#remoteControlBox').attr('class', 'remoteMapControlBox');
		}
		else if (event.keyCode == 39) {
			if ($(selectedMap).attr('name') == 'page') addPageInsidePlayList($(selectedMap).attr('title'), $('#'+$(selectedMap).attr('id')).attr('info'), null,  $('#'+$(selectedMap).attr('id')).attr('edit'));
			else if ($(selectedMap).attr('name') == 'content') addToPlayList($(selectedMap).attr('id'));
			$('#remoteControlBox').attr('class', 'remoteMapControlBox');
		}
		else if (event.keyCode == 37) {
			
			$('#remoteControlBox').attr('class', 'remotePLControlBox');
			$('#glows_'+selectedMapID).hide();
			$('#shadows_'+selectedMapID).show();
			$('#'+currentSelection).css('border', '2px solid #1288ff');
		}
		else if (event.keyCode == 38) {
			setVolume(getVolume()+10);
		}
		else if (event.keyCode == 40) {
			setVolume(getVolume()-10);
		}
	}
	else if ($(remoteControlBox).attr('class') == 'remotePLControlBox') {
		
		if (event.keyCode == 37) {
			previousVideo();
		}
		else if (event.keyCode == 39) {
			nextVideo();
		}
		else if (event.keyCode == 38) {
			setVolume(getVolume()+10);
		}
		else if (event.keyCode == 40) {
			setVolume(getVolume()-10);
		}
		else if (event.keyCode == 13) {
			if (getPlayerState() == 2) play();
			else if (getPlayerState() == 1) pause();
		}
		else if (event.keyCode == 32) {
			$('#remoteControlBox').attr('class', 'remotePLMenuBox');
		}
	}
	else if ($(remoteControlBox).attr('class') == 'remotePLMenuBox') {
		
		if (event.keyCode == 13) {
			$('#remoteControlBox').attr('class', 'remotePLControlBox');
		}
		else if (event.keyCode == 37 || event.keyCode == 39) {
			$('#remoteControlBox').attr('class', 'remoteMapControlBox');
			$('#glows_'+selectedMapID).show();
			$('#shadows_'+selectedMapID).hide();
			$('#'+currentSelection).css('border','none');
		}
		else if (event.keyCode == 38) {
			var playerContainer = $('#playerContainer');
			playerWidth = $(playerContainer).css('width');
			playerHeight = $(playerContainer).css('height');
			$(playerContainer).attr('class', 'playerContainerFull');
			$(playerContainer).css('width',$(document).width());
			$(playerContainer).css('height',$(document).height());	
			$('#myytplayer').attr('width', $(document).width());
			$('#myytplayer').attr('height', $(document).height());
			$('#remoteControlBox').attr('class', 'fullScreenControlBox');
		}
	}
	else if ($(remoteControlBox).attr('class') == 'fullScreenControlBox') {
		if (event.keyCode == 37) {
			previousVideo();
		}
		else if (event.keyCode == 39) {
			nextVideo();
		}
		else if (event.keyCode == 38) {
			setVolume(getVolume()+10);
		}
		else if (event.keyCode == 40) {
			setVolume(getVolume()-10);
		}
		else if (event.keyCode == 13) {
			if (getPlayerState() == 2) play();
			else if (getPlayerState() == 1) pause();
		}
		else if (event.keyCode == 32) {
			$('#playerContainer').attr('class', 'playerContainerRegular');
			$('#playerContainer').css('width', playerWidth);
			$('#playerContainer').css('height', playerHeight);
			
			$('#myytplayer').attr('width', playerWidth);
			$('#myytplayer').attr('height', playerHeight);
			$(remoteControlBox).attr('class', 'remotePLControlBox');
		}
	}
}

function searchCoordinatesAndSize(mapWidth, mapHeight, searchX, searchY) {
	$('.map').each(function(){
		var offset = $(this).offset();
		var thisWidth = $(this).attr('offsetWidth');
		var thisHeight = $(this).attr('offsetHeight');
		var thisLeft = offset.left - boxleft;
		var thisRight = thisLeft + thisWidth;
		var thisTop = offset.top - boxtop; 
		var thisBottom = thisTop + thisHeight;
	
		if (thisWidth < mapWidth * 1.1 && thisWidth > mapWidth * .9 && thisLeft < searchX && thisRight > searchX && thisBottom > searchY && thisTop < searchY) {
			selectMap(this);
			return false;
		}
	});
}

function selectMap(mapToSelect) {
	selectedMap = $('#'+selectedMapID);
	if (selectedMap!=null) {
		$('#shadows_'+selectedMapID).show();
		$('#glows_'+selectedMapID).hide();
	}	
	selectedMap = mapToSelect;
	selectedMapID = $(selectedMap).attr('id');
	$('#shadows_'+selectedMapID).hide();
	$('#glows_'+selectedMapID).show();
	var offset = $(selectedMap).offset();
	var selectedTop = offset.top - boxtop;
	var selectedHeight = $(selectedMap).attr('offsetHeight');
	var selectedWidth = $(selectedMap).attr('offsetWidth');
	
	var selectedLeft = $(document).width()/2 - selectedWidth/2 - boxleft;
	
	if (level == 2) animateInterval = setInterval("waitToAnimate('"+selectedMapID+"', "+selectedHeight+", "+selectedLeft+", "+selectedTop+");", 10);
	else if (selectedHeight > boxheight / 3) onNodeClick(selectedMapID);
}

function waitToAnimate(id, height, left, top){
	if (animating == false) {
		clearInterval(animateInterval);
		setAnimation(id, height, left, top);
	}
}

function resizeBrowserWindow(e){
	var windowHeight = $(window).height();
	var windowWidth = $(window).width();
	var heightScale = (windowHeight - boxtop)/boxheight;
	if (boxheight >= 505 && boxheight * heightScale >= 505) {
		$('#thebox').css('height', windowHeight - boxtop);
		$('#thebox').css('width', windowWidth - boxleft);	
		scaleHeight(heightScale);
		boxheight = windowHeight - boxtop;
		boxwidth = windowWidth - boxleft;
	}	
}

function loadStats(uid) {
	onInit();
	
	url = getBaseURL('/scripts/header.php');
	if (uid == sessionUserID) var headerUrl = url+'&floType=homePage&category=Stats&subCategory=default';
	else var headerUrl = url+'&floType=Stats&category=Stats&subCategory=Stats&info='+uid;
	
	$.ajax({
		url: headerUrl,
		success: function(html){
			$('#headerContainer').html(html);
		}
	});
	
	$('#dragTip').hide();
	$('#addAllHomeStuff').remove();
	
	url = getBaseURL('/ajax/loadStats.php');
	$.ajax({
		url: url+'&uid='+uid,
		type: 'html',
		success: function(html){
			$('#thebox').append(html);
		}
	});		
}

function initializeAdjacentMaps() {
	leftMapID = null;
	rightMapID = null;
	topMapID = null;
	bottomMapID = null;
}

function createViewport(initialmapratio) {
	if ($('#thebox').css('left') == '350px') { 
		boxwidth = $(window).width() - boxleft;
		boxheight = $(window).height() - boxtop	;
		$('#thebox').css('width', boxwidth);
		$('#thebox').css('height', boxheight);
	}
	else {
		boxwidth = 760;
		boxheight = parseFloat($('#thebox').css('height').split('px')[0]);
	}
	initialheight = boxheight;
	initialwidth = initialmapratio * initialheight;

	vpleft = boxwidth/2 - vpwidth/2;
	vptop = boxheight/2 - vpheight/2;
	vpStartX = vpleft;
	
	$('#viewport').css('width', vpwidth);
	$('#viewport').css('height', vpheight);
	$('#viewport').css('left', vpleft);
	$('#viewport').css('top', vptop);
	$('#thebox').unbind('mousedown', determineDrag);
	$('#thebox').bind('mousedown', determineDrag);
	$('#thebox').unbind('mousemove', trackMousePosition);
	$('#thebox').bind('mousemove', trackMousePosition);
}

function setAnimation(id, fheight, xtogo, ytogo) {
	animating = true;	
	var map = $('#'+id);
	var offset = $(map).offset();
	
	xstart = offset.left - boxleft;
	ystart = offset.top - boxtop; 
	totaldx = xtogo - xstart;
	totaldy = ytogo - ystart;
	totaldh = fheight - $(map).attr('offsetHeight');
	if (Math.abs(totaldh) > 10) {
		level = parseInt($(map).css('z-index')) + 1;
		hideForAnimation();
	}	

	framedx = totaldx / totalframes;
	framedy = totaldy / totalframes;
	framedh = totaldh / totalframes; 
	framenumber = 0;
	
	if (frame == false) frameInterval = setInterval("animateNode('"+id+"');", 30);
}

function hideForAnimation() {
	$('.mapControls').hide();
	$('.pageMapHeader').remove();
	$('.mapStuff').hide();
}

function animateNode(id) {
	frame = true;
	var element = $('#'+id);
	var dscale = (framedh + $(element).attr('offsetHeight')) / $(element).attr('offsetHeight');
	if (Math.round(dscale * 10) != 10) scaleNodes(dscale);
	
	var offset = $(element).offset();
	var movetox = xstart + (framedx * (framenumber + 1));
	var movetoy = ystart + (framedy * (framenumber + 1));
	var movefromx = (offset.left - boxleft);
	var movefromy = (offset.top - boxtop);
	var vpdx =  movetox - movefromx;
	var vpdy = movetoy - movefromy;
	if (Math.round(dscale * 10) != 10) moveMaps(vpdx, vpdy);
	else moveViewport(vpdx, vpdy);
	framenumber++;
	frame = false;
	
	if (framenumber >= totalframes) {
		clearInterval(frameInterval);
		initializeAdjacentMaps();
		checkSizeAndPosition($(element));
		$('.map').each(function(){
			map = $('#'+this.id);
			if ($(map).attr('id') != id && $(map).length > 0 && 
					(parseInt($(map).css('z-index')) < level || Math.round(dscale * 10) != 10)) checkSizeAndPosition(map);
		});	
		animating = false;
		if (level == 2) {
			var mainMapOffset = $('#p_0').offset();
			mapStartX = mainMapOffset.left - 350;
			vpStartX = vpleft;
		}
	}	
}

function scaleNodes(scale) {
	$('#viewport').children('.map').each(function() {
		$(this).css('width', scale * parseFloat($(this).css('width').split('px')[0]));
		$(this).css('height', scale * parseFloat($(this).css('height').split('px')[0]));
		$(this).css('left', scale * $(this).attr('offsetLeft'));
		$(this).css('top', scale * $(this).attr('offsetTop'));
	});	
}

function scaleHeight(scale){
	var childMap = $('#viewport').children('.map')[0];
	var childMapID = $(childMap).attr('id');
	$('#viewport').children('.map').each(function() {
		$(this).css('width', scale * parseFloat($(this).css('width').split('px')[0]));
		$(this).css('height', scale * parseFloat($(this).css('height').split('px')[0]));
		if ($(this).attr('id') != childMapID) {
			$(this).css('left', scale * $(this).attr('offsetLeft'));
			$(this).css('top', scale * $(this).attr('offsetTop'));
		}
	});	
}

function moveMaps(dx, dy) {
	$('#viewport').children('.map').each(function(){
		$(this).css('left', dx + $(this).attr('offsetLeft'));
		$(this).css('top', dy + $(this).attr('offsetTop'));
	});
}

function determineDrag(event){
	dragx = event.clientX;
	dragy = event.clientY;
	startDragX = dragx;
	startDragY = dragy;
	document.onselectstart = function() {return false;} // ie
	document.onmousedown = function() {return false;} // mozilla
	if (level == 2) {
		allowDrag = true;
		firstMove = true;
		mouseUp = false;
	}
	else allowDrag = false;
}

function trackMousePosition(event) {
	if (allowDrag == true) {
		currentMouseX = event.clientX;
		if (firstMove == true) 	{
			$('#dragTip').remove('#dragTip');
			clearInterval(dragInterval);
			if (browserVersion == 'msie' && currentPlayerState == 1 ) dragInterval = setInterval('physicsDrag();', 110);
			else dragInterval = setInterval('physicsDrag();', 15);
			$('#thebox').unbind('mouseup', doNothing);
			$('#thebox').bind('mouseup', endDragMouseUp);
			firstMove = false;
		}	
		changeMomentum();
	}	
}

function changeMomentum() {
	if (currentMouseX > dragx) var dx = 6 * Math.pow(currentMouseX - dragx, .5);
	else var dx = -6 * Math.pow(dragx - currentMouseX, .5);
	dragx = currentMouseX;
	dragMomentum = dragMomentum + dx;
}

function physicsDrag() {
	moveViewport(dragMomentum * (2/3), 0);
	dragMomentum = dragMomentum/1.18;
	
	var dragDistance = (vpStartX - mapStartX) - vpleft;
	var newPageBlockIndex = Math.max(0, Math.floor(dragDistance / pageBlockLength));
	if (currentPageBlockIndex != newPageBlockIndex) {
		currentPageBlockIndex = newPageBlockIndex;
		dragLoadPosition(newPageBlockIndex);
	}
	
	if (Math.abs(dragMomentum) < 7) {
		if (allowDrag == false) clearInterval(dragInterval);
		dragRemoveMaps();
	}
}

function dragLoadPosition(pageBlockIndex) {
	if ($('#pb_0').attr('name') == 'pageblock') {
		var nextBlock = pageBlockIndex + 1;
		var previousBlock = pageBlockIndex - 1;
		var nextNextBlock = pageBlockIndex + 2;
		if ($('#pb_'+pageBlockIndex).attr('loaded') == 'false') loadRelatedMaps($('#pb_'+pageBlockIndex));
		else if ($('#pb_'+pageBlockIndex).attr('loaded') == 'true') {
			$('#pb_'+pageBlockIndex).children('.hiddenMap').each(function(){
				$(this).attr('class', 'map');
				$(this).show();
			});
		}
		if ($('#pb_'+nextBlock).length > 0 && $('#pb_'+nextBlock).attr('loaded') == 'false') loadRelatedMaps($('#pb_'+nextBlock));
		else if ($('#pb_'+nextBlock).attr('loaded') == 'true') {
			$('#pb_'+nextBlock).children('.hiddenMap').each(function(){
				$(this).attr('class', 'map');
				$(this).show();
			});
		}
		if ($('#pb_'+previousBlock).length > 0 && $('#pb_'+previousBlock).attr('loaded') == 'true') {
			$('#pb_'+previousBlock).children('.map').each(function(){
				$(this).attr('class', 'hiddenMap');
				$(this).hide();
			});
		}	
		if ($('#pb_'+nextNextBlock).length > 0 && $('#pb_'+nextNextBlock).attr('loaded') == 'true') {
			$('#pb_'+nextNextBlock).children('.map').each(function(){
				$(this).attr('class', 'hiddenMap');
				$(this).hide();
			});
		}	
	}
	else if ($('#pb_0').attr('name') == 'doublepagestrip') {
		pageBlockIndex = pageBlockIndex * 2;
		var nextBlock = pageBlockIndex + 1;
		var nextBlock2 = pageBlockIndex + 2;
		var nextBlock3 = pageBlockIndex + 3;
		if ($('#pb_'+pageBlockIndex).attr('loaded') == 'false') loadRelatedMaps($('#pb_'+pageBlockIndex));
		if ($('#pb_'+nextBlock).attr('loaded') == 'false') loadRelatedMaps($('#pb_'+nextBlock));
		if ($('#pb_'+nextBlock2).length > 0 && $('#pb_'+nextBlock2).attr('loaded') == 'false') loadRelatedMaps($('#pb_'+nextBlock2));
		if ($('#pb_'+nextBlock3).length > 0 && $('#pb_'+nextBlock3).attr('loaded') == 'false') loadRelatedMaps($('#pb_'+nextBlock3));
	}
}

function dragRemoveMaps() {
	if ($('#pb_0').attr('name') == 'pageblock') {
		var nextBlock = currentPageBlockIndex + 1;
		$('#p_0').children('.map').each(function(){
			map = $('#'+this.id);
			var pbIndex = parseInt(this.id.split('_')[1]);
			if (pbIndex != currentPageBlockIndex && pbIndex != nextBlock && $(map).attr('loaded') == 'true') removeMapChildren(this.id);
		});
	}
	else if ($('#pb_0').attr('name') == 'doublepagestrip') {
		var pageBlockIndex = currentPageBlockIndex * 2;
		$('#p_0').children('.map').each(function(){
			var pbIndex = parseInt(this.id.split('_')[1]);
			if (pbIndex < pageBlockIndex || pbIndex > pageBlockIndex + 3) removeMapChildren(this.id); 
		});
	}
}

function endDragMouseUp() {
	allowDrag = false;
	firstMove = false;
	document.onselectstart = function() {return true;} // ie
	document.onmousedown = function() {return true;} // mozilla
	$('#thebox').unbind('mouseup', endDragMouseUp);
	$('#thebox').bind('mouseup', doNothing);
}

function doNothing(event) {
	allowDrag = false;
	firstMove = false;
	document.onselectstart = function() {return true;} // ie
	document.onmousedown = function() {return true;} // mozilla
	removeAutoCompleteBox();
}

function moveViewport(dx, dy) {
	vpleft = vpleft + dx;
	vptop = vptop + dy;
	$('#viewport').css('left', vpleft);
	$('#viewport').css('top', vptop);
}

function onNodeClick(id) {
	if ((dragx == startDragX && dragy == startDragY && !id.match(centermap)) || $('#remoteModeButton').attr('class') == 'remoteModeButtonSelect') {
		$('#dragTip').remove('#dragTip');
		$('#thebox').children('.scrollArrow').hide();
		clearInterval(dragInterval);
		if (animating == false) {
			animating = true;
			
			var parentMap = $('#'+id).parent();
			var grandParentMap = $(parentMap).parent();
			if ($(grandParentMap).attr('name') == 'pageblock' || $(grandParentMap).attr('name') == 'singlepagestrip' ||
					$(grandParentMap).attr('name') == 'doublepagestrip') {
				$(grandParentMap).siblings('.map').each(function(){
					$(this).remove('#'+this.id);
				});
				$(grandParentMap).parent().attr('loaded', 'partial');
			}
			
			if ($(parentMap).attr('name') == 'pageblock' || $(parentMap).attr('name') == 'singlepagestrip' ||
					$(parentMap).attr('name') == 'doublepagestrip') {
				$(parentMap).siblings('.map').each(function(){
					$(this).children('.map').each(function(){
						$(this).remove('#'+this.id);
					});
					$(this).attr('loaded', 'false');
				});
			}	
			else if ($(parentMap).attr('name') == 'page') {
				$(parentMap).siblings('.map').each(function(){
					$(this).remove('#'+this.id);
				});
				$(grandParentMap).attr('loaded', 'partial');
			}
			$('#'+id).siblings('.map').each(function(){
				if (!this.id.match(centermap)) {
					$(this).children('.map').each(function(){
						$(this).remove('#'+this.id);
					});
					$(this).attr('loaded', 'false');
				}	
			});
			centermap = id;

			if ($('#'+id).attr('name') == 'page' || $('#'+id).attr('name') == 'content') setAnimation(id, boxheight * .65, boxwidth/2 - (boxheight * .65 * 1.75)/2, boxheight * .12);
		}
	}
}

function goBack(id) {
	var map = $('#'+id);
	initializeAdjacentMaps();
	$('#thebox').children('.scrollArrow').hide();
	if (animating == false) {
		animating = true;
		$('#'+id).siblings('.map').each(function(){
			if ($(this).attr('name') == 'page') {
				$(this).children('.map').each(function(){
					$(this).remove('#'+this.id);
				});
				$(this).attr('loaded', 'false');
			}	
		});
		$('#'+id).children('.map').each(function(){
			$(this).remove('#'+this.id);
		});
		$(map).attr('loaded', 'false');
		if ($(map).parent().attr('name') == 'page') centermap = $(map).parent().attr('id');
		var returnX = 200 - parseFloat($(map).attr('x')) * pageBlockLength;

		if ($(map).parent().attr('name') == 'pageblock') setAnimation($(map).parent().attr('id'), boxheight, returnX, 0);
		else if ($(map).parent().attr('name') == 'doublepagestrip') setAnimation($(map).parent().attr('id'), boxheight * (2/3), returnX, 0);
		else if ($(map).parent().attr('name') == 'singlepagestrip') setAnimation($(map).parent().attr('id'), boxheight * (1/3), returnX, boxheight * (2/3));	
		else setAnimation($(map).parent().attr('id'), boxheight * .65, boxwidth/2 - (boxheight * .65 * 1.75)/2, boxheight * .12);
	}	
}

function checkSizeAndPosition(map) {
	var offset = $(map).offset();
	var mapleft = offset.left - boxleft;
	var mapright = mapleft + $(map).attr('offsetWidth');
	var maptop = offset.top - boxtop; 
	var mapbottom = maptop + $(map).attr('offsetHeight');
	var mapsize =  $(map).attr('offsetHeight');	
	
	if (mapright < - boxwidth || mapbottom < -boxheight/2 || mapleft > boxwidth * 2 || maptop > boxheight * 1.5) var inscreen = false;
	else var inscreen = true;
	
	if (inscreen == true) {
		if (mapsize > boxheight/3 && mapsize < boxheight && ($(map).attr('name') == 'page' || $(map).attr('name') == 'content')) {
			if (maptop < boxheight/2 && mapbottom > boxheight/2) {
				if (mapleft < -boxwidth/2 && mapright > -boxwidth/2) {
					leftMapID = $(map).attr('id');
					$('#leftArrowText').text($(map).attr('title'));
					var leftScroll = $('#leftScroll');
					$(leftScroll).attr('href', "javascript:onNodeClick('"+$(map).attr('id')+"');");
					$(leftScroll).css('left', boxwidth/2 - (boxheight * .65 * 1.75)/2 - 80);
					$(leftScroll).show();
				}	
				else if (mapleft < boxwidth * (1.5) && mapright > boxwidth * (1.5)) {
					rightMapID = $(map).attr('id');
					$('#rightArrowText').text($(map).attr('title'));
					var rightScroll = $('#rightScroll');
					$(rightScroll).attr('href', "javascript:onNodeClick('"+$(map).attr('id')+"');");
					$(rightScroll).css('left', boxwidth/2 - (boxheight * .65 * 1.75)/2 + boxheight * .65 * 1.75 + 20);
					$(rightScroll).show();
				}	
			}
			else if (mapleft < boxwidth/2 && mapright > boxwidth/2) {
				if (maptop > -boxheight * 1.5 && mapbottom < 0) {
					topMapID = $(map).attr('id');
					$('#topArrowText').text($(map).attr('title'));
					var topScroll = $('#topScroll');
					$(topScroll).attr('href', "javascript:onNodeClick('"+$(map).attr('id')+"');");
					$(topScroll).css('top', boxheight * .12 - 50);
					$(topScroll).show();
				}	
				else if (maptop > boxheight && mapbottom < boxheight * 2.25) {
					bottomMapID = $(map).attr('id');
					$('#bottomArrowText').text($(map).attr('title'));
					var bottomScroll = $('#bottomScroll');
					$(bottomScroll).attr('href', "javascript:onNodeClick('"+$(map).attr('id')+"');");
					$(bottomScroll).css('top', boxheight * .12 + boxheight * .65 + 60);
					$(bottomScroll).show();
				}	
			}
		} 
		
		if ($(map).attr('loaded') == 'false' && mapsize >= boxheight/5) {
			if ($(map).attr('name') != 'page' && $(map).attr('name') != 'content') loadRelatedMaps(map);
			else if ($(map).attr('name') == 'page' && ($(map).attr('id').match(centermap) || $(map).attr('id').match(leftMapID) || 
					$(map).attr('id').match(rightMapID) || $(map).attr('id').match(topMapID) || $(map).attr('id').match(bottomMapID))) {
				loadRelatedMaps(map);
			}	
		}	
		if (!$(map).attr('id').match(centermap) && level == 2 && mapleft < boxwidth/2 && mapright > boxwidth/2 && mapsize > boxheight/3
				&& $(map).attr('name') != 'initialpage' && $(map).attr('name') != 'page' && $(map).attr('name') != 'content') {
				centermap = $(map).attr('id');
		}
		if (($(map).attr('name') == 'page' || $(map).attr('name') == 'content') && level != 2  && ($(map).attr('id').match(centermap) || $(map).attr('id').match(leftMapID) || 
				$(map).attr('id').match(rightMapID) || $(map).attr('id').match(topMapID) || $(map).attr('id').match(bottomMapID))) {
			showFullMap(map);
		}	
		
		if ($(map).attr('loaded') == 'partial' && mapsize >= boxheight/5 && mapsize < boxheight * 5) mergeRelatedMaps(map);
		
		if (mapsize > boxheight * 1.25) hideMap(map);	
	}
	if (mapsize < boxheight/15) {
		removeMap($(map).attr('id'));
		return;
	}	
	if (mapsize < boxheight/3) showMapImage(map);
	
	if (inscreen == false) {
		if ($(map).attr('loaded') != "false") removeMapChildren($(map).attr('id'));
		if (mapsize > boxheight * 5) {
			removeMap($(map).attr('id'));
			return;
		}	
	}	
	if ($(map).attr('offsetWidth') > removeSize) removeLargeMap(map);
	else if ($(map).attr('offsetWidth')/parseFloat($(map).attr('scale')) < removeSize && $('#'+$(map).attr('parent')).attr('class') == 'hiddenmap') returnMapParent(map);	
}

function returnMapParent(map) {
	var pid = $(map).attr('parent');
	$('#'+pid).show();
	var parentMap = $('#'+pid);
	$(parentMap).css('width', parseFloat($(map).css('width').split('px')[0])/parseFloat($(map).attr('scale')));
	$(parentMap).css('height', $(parentMap).attr('offsetWidth')/parseFloat($(parentMap).attr('ratio')));
	var parentLeft = parseFloat($(map).attr('x')) * $(parentMap).attr('offsetWidth');
	var parentTop = parseFloat($(map).attr('y')) * $(parentMap).attr('offsetWidth');
	$(parentMap).css('left', parseFloat($(map).css('left').split('px')[0]) - parentLeft);
	$(parentMap).css('top', parseFloat($(map).css('top').split('px')[0]) - parentTop);
	$('#viewport').children('.map').each(function(){
		$('#'+pid).append($(this));
		$(this).css('left', parseFloat($(this).attr('x')) * 100 + '%');
		$(this).css('top', parseFloat($(this).attr('y')) * 100 * parseFloat($(parentMap).attr('ratio')) + '%');
		$(this).css('width', parseFloat($(this).attr('scale')) * 100 + '%');
		$(this).css('height', parseFloat($(this).attr('scale'))/parseFloat($(this).attr('ratio')) * parseFloat($(parentMap).attr('ratio')) * 100 + '%');
	});
	$(parentMap).attr('class', 'map');
	$(parentMap).attr('loaded', 'partial');
}

function removeLargeMap(map) {
	$(map).children('.map').each(function(){
		if ($('#'+this.id).length > 0) {
			$(this).css('left', $(this).attr('offsetLeft') + $(map).attr('offsetLeft') + 'px');
			$(this).css('top', $(this).attr('offsetTop') + $(map).attr('offsetTop') + 'px');
			$(this).css('width', $(this).attr('offsetWidth') + 'px');
			$(this).css('height', $(this).attr('offsetHeight') + 'px');
			$('#viewport').append($(this));
		}	
	});
	$(map).attr('class', 'hiddenmap');
	$(map).html(jQuery.trim($(map).html()));
	$(map).hide();
}

function removeMapChildren(id) {
	$('#'+id).children('.map, .hiddenMap').remove();
	$('#'+id).attr('loaded', 'false');
}

function hideMap(map) {
	$('#mapStuff_'+$(map).attr('id')).hide();
	$('#mapimage_'+$(map).attr('id')).hide();
}

function showFullMap(map) {
	var id = $(map).attr('id');	
	var mapimage = $('#mapimage_'+id);
	
	url = getBaseURL('/ajax/mapControls.php');
	url = url+'&id='+id+'&dbid='+$(map).attr('info')+'&title='+$(map).attr('title')+'&rating='+$(map).attr('rating');

	$.ajax({
		url: url,
		type: 'html',
		success: function(html){
			$('#mapControls_'+id).html(html);

			$('#mapControls_'+id).show();
			$('#mapStuff_'+id).hide();

			if ($(map).attr('name') == 'page') {
	
				$(mapimage).show();
				$(mapimage).children('.m_thumbnail').fadeOut('slow', function(){
					$(mapimage).children('.m_thumbnail').hide();
				});
			}
			else if ($(map).attr('name') == 'content') {
				$('#img_'+id).show();
			}
		}
	});
}

function showMapImage(map) {
	var id = $(map).attr('id');
	$('#mapControls_'+id).empty();
	$('#mapControls_'+id).hide();
	$('#mapStuff_'+id).show();

	if ($(map).attr('name') == 'page') {
		var mapimage = $('#mapimage_'+id);
		$(mapimage).show();
		$(mapimage).children('.m_thumbnail').show();
	}
	else if ($(map).attr('name') == 'content') {
		$('#img_'+id).show();
	}
}

function removeMap(id) {
	var pid = $('#'+id).attr('parent');
	$('#'+id).remove('#'+id);
	if ($('#'+pid).length > 0) {
		if ($('#'+pid).children('.map').length > 0) $('#'+pid).attr('loaded', 'partial');
		else if ($('#'+pid).children('.map').length == 0) $('#'+pid).attr('loaded', 'false');	
	}	
}

function createInitialMap() {
	$('#viewport').children('.map').each(function(){
		$(this).css('width', initialwidth); 
		$(this).css('height', boxheight); 
		$(this).css('left', - vpleft); 
		$(this).css('top', - vptop); 
				
		checkSizeAndPosition($(this));
	});
}

function loadContentBlock(id, dir) {	
	$('.pageMapHeader').remove();
	var page = $('#'+id).attr('page');
	if (dir == "up" && Math.ceil($('#'+id).attr('content')/8) > parseInt($('#'+id).attr('page')) + 1) page++;		
	else if (dir == "down" && $('#'+id).attr('page') != 0) page--;
	$('#'+id).attr('page', page);
	$('#'+id).attr('offsetindex', page);
	removeMapChildren(id);
	loadRelatedMaps($('#'+id));	
}

function updateHash(mapid, mid) {

	if (floType=="floPage" && (mid=="pb" || mid=="p")) {
		window.location.hash = "page#"+topMapID;
		mid = topMapID;
	}
	else {
		if (mid!="pb" && mid!="p") window.location.hash = "page#"+mid;
		else {
			if (currentCategory!='default' || currentSubCategory!='default') {
				var hash;
				if (currentCategory!='default')	hash = "category#"+currentCategory;
				if (currentSubCategory!='default') hash = hash + "#subCategory#"+currentSubCategory;
				window.location.hash = hash;
			}
			else window.location.hash = ' ';
		}
	}
}

function loadInitialMaps(type, category, subCategory, orderby, info) {
	floType = type;
	if (orderby == null) orderby = "default";
	if (category == null && mainCategory == 'Music') category = "default";
	else if (category == null && mainCategory == 'Video') category = "none";
	var subCategory = (subCategory == null) ? "default" : subCategory;

	centermap = null;
	currentCategory = category;
	currentSubCategory = subCategory;
	topMapID = info;
	
	if (floType != 'floCreate') $('#maploader').show();

	onInit();
	
	url = getBaseURL('/ajax/controller/mapcontroller.php');
	var url = url+'&id=-1&offsetIndex=0&mapType=initial&floType='+floType+'&category='+
			currentCategory+'&subCategory='+currentSubCategory+'&orderby='+orderby;
	if (info!=null) url = url+'&info='+info;
	
	headerUrl = getBaseURL('/scripts/header.php');
	var headerUrl = headerUrl+'&floType='+floType+'&category='+ currentCategory+'&subCategory='+currentSubCategory+'&orderby='+orderby;
	if (info!=null) headerUrl = headerUrl+'&info='+info;
	
	$.ajax({
		url: headerUrl,
		success: function(html){
			$('#headerContainer').html(html);
		}
	});
	
	$.ajax({
		url: url,
		success: function(html){
			$('#thebox').append(html);
			createViewport($('#p_0').attr('ratio'));
			createInitialMap();	
			if (firstLoad == true) {
				docReady();
				$('#dragTip').show();
				if (floType == 'floPage' && subCategory != 'People' && $('#p_0').attr('flotype')!='homePage') {
					addSinglePageToPlayList(info);
					if ($('#fbcss').length > 0)  FB.CanvasClient.scrollTo(0, 420);
				}
				else if (initialVideo!=null) {
					loadNewVideo(initialVideo, '0');
					if ($('#fbcss').length > 0)  FB.CanvasClient.scrollTo(0, 420);
				}
				firstLoad=false;
			}
		}
	});
}

function mergeRelatedMaps(map) {
	var id = $(map).attr('id');
	var offsetIndex = $(map).attr('offsetindex');
	if ($(map).attr('orderby')==null) orderby = 'default';
	else orderby = $(map).attr('orderby');
	
	url = getBaseURL('/ajax/controller/mapcontroller.php');
	$.ajax({
		url: url+'&id='+id+'&offsetIndex='+offsetIndex+'&mapType='+
		$(map).attr('nextmaptype')+'&floType='+$(map).attr('flotype')+'&category='+
		$(map).attr('category')+'&subCategory='+$(map).attr('subcategory')+'&info='+
		$(map).attr('info')+'&ratio='+parseFloat($(map).attr('ratio'))+'&parentWidth='+
		$(map).attr('offsetWidth')+'&zIndex='+$(map).css('z-index')+'&orderby='+orderby,
		type: 'html', 
		success: function(html) {	
		
			var repeatMaps = new Array();
			
			$('#'+id).children('.map').each(function(){
				var mapx = Math.round(parseFloat($(this).attr('x')) * 1000);
				var mapy = Math.round(parseFloat($(this).attr('y')) * 1000);
				
				$(html).each(function(){
					if (Math.round(parseFloat($(this).attr('x')) * 1000) == mapx && Math.round(parseFloat($(this).attr('y')) * 1000) == mapy)	{
						repeatMaps.push(this.id);	
						return;
					}
				});
			});
			$('#'+id).prepend(html);
			$(map).attr('loaded', 'true');
			
			for (i = 0; i < repeatMaps.length; i++) {
				$('#'+repeatMaps[i]).remove('#'+repeatMaps[i]);
			}	
			initializeAdjacentMaps();
			$('#'+id).children('.map').each(function() {
				map = $('#'+this.id);
				if ($(map).length > 0) checkSizeAndPosition(map);
			});
			
			$('#'+id).html(jQuery.trim($('#'+id).html()));
		}
	});
}

function loadRelatedMaps(map) {
	var id = $(map).attr('id');
	if (level == 2 && id == 'pb_0') pageBlockLength = boxheight * 2;
	$(map).html(jQuery.trim($(map).html()));
	//$('img[name=loader_'+id+']').show();
	var offsetIndex = $(map).attr('offsetindex');
	if ($(map).attr('orderby')==null) orderby = 'default';
	else orderby = $(map).attr('orderby');
	
	url = getBaseURL('/ajax/controller/mapcontroller.php');
	$.ajax({
		url: url+'&id='+id+'&offsetIndex='+offsetIndex+'&mapType='+$(map).attr('nextmaptype')+
		'&floType='+$(map).attr('flotype')+'&category='+$(map).attr('category')+'&subCategory='+
		$(map).attr('subcategory')+'&info='+$(map).attr('info')+'&ratio='+
		parseFloat($(map).attr('ratio'))+'&parentWidth='+$(map).attr('offsetWidth')+'&zIndex='+
		$(map).css('z-index')+'&orderby='+orderby,
		success: function(html) {
					$(map).append(html);
					$(map).attr('loaded', 'true');
					if ($(map).css('z-index') < 1) {
						$(map).children('.map').each(function() {
							map = $('#'+this.id);
							if ($(map).length > 0) checkSizeAndPosition(map);
						});
					}	
					$('#maploader').hide();
					$('img[name=loader_'+id+']').hide();
				}
	});
}