var cli_timeout;
var cli_timeout_value;

/*if(typeof(CollapsedContent) == 'undefined'){
	document.write('<script type="text/javascript" src="http://www.richmond.edu/_common_/scripts/jquery-collapsable-content.js"></script>');
}*/
/* ###############################################
 * ################  Maps Class  #################
 * ###############################################
 */
function Maps(){	
	var obj = this;
	
	this.buildingsConfiguration = {
			xmlUrl: false,
			node: 'building',
			indexAttr: 'number'
	};			
	
	this.mobile = false;
	
	$('.mobile').ready(function(){
		if( $('body.mobile').length > 0){
			obj.mobile = true;
			obj.__construct();
		}	
	});
		
	this.domain = 'http://www.richmond.edu/visit/maps/';	
	
	this.defaults = {
		view: 'maps',
		maps: 'landmarks',
		building: '05',
		showPopup: false
	};
	
	this.dimensions = {
		categoryMenuHeight: 190,
		locationsMenuHeight: 150
	}
	
	this.__construct = function(){
		var obj = this;
		
		obj.controls = new Maps_Controls();
		obj.buildings = new Maps_Buildings();
		obj.directory = new Maps_Directory();
		
		obj.buildings.__construct(obj);
		

	}	
}


/* #############################################
 * ################  Controls  #################
 * #############################################
 */
function Maps_Controls(){
	this.parent;
	this.viewState;
	this.mapbox;
	this.mapsState;
	this.clickType = false;
	this.hotspot = ".hotspot";
	this.imageLevels = "#maplevel";
	this.selectedAreaImage = "#picturebox-main";
	this.selectedAreaContent = "#summary .content";
	
	this.moving = false;
	
	this.navigation = {
		main: '#vtour-nav',
		secondary: '#listbox-nav',
		zoom: '#zoom-controls',
		locations: "#locations",
		categories: "#category",
		secondary_content: "#listbox-content",
		maps: "#maps-nav"
	};
	
	this.zoomControl = {
		plus: "#zoom",
		minus: "#back",
		levels: ".zoom-level",
		slider: "#zoomslider",
		sliderActive: false,
		parent: "#zoom-controls"
	}
	
	this.viewport = {
			id: ".viewport",
			widthStandard: $(".viewbox:first").width(),
			heightStandard: $(".viewbox:first").height() ,
			widthSmall: $(".viewbox:first").width() - 120,
			heightSmall: $(".viewbox:first").height() - 222
	};
	
	this.zoom = {
		level: 0,
		max: 2
	};	
	
	this.multipliers = {
		tour : new Array(.5, .75, 1),
		maps : new Array(.44, .6666667, 1) //correspond to zoom levels
	}
	
	this.coordinates = {
			x: 0,
			y: 0
	};
	
	this.center = {
			x: 0,
			y: 0
	};
	
	this.thumbnails = {
		id: '#picturebox-thumbnails',
		containers: '.picturebox-thumb',
		displayMax: 4,
		xmlSet: false,
		height: '76px',
		width: '119px',
		nextButtonUrl: 'http://'+window.location.hostname+'/_common_/images/_global_/maps/next.jpg'
	};	
	
	
	this.gmap = {
			id: "#gmap",
			zoomFactor: 16, 
			url: 'http://maps.google.com/maps/api/staticmap?size='+this.viewport.widthStandard+'x'+(this.viewport.heightStandard - 32)+'&maptype=satellite&sensor=false',
			appUrl: 'http://www.google.com/maps?ie=UTF8&spn=0.003899,0.00419&t=h',
			html:'<img width="'+this.viewport.widthStandard+'" height="'+(this.viewport.heightStandard - 32)+'" src=""/><p class="tiny">Satellite imagery uses a different orientation from the standard campus maps.</p>'
	};
	this.setSearch = maps_setSearch;
	this.checkLookupItems = maps_checkLookupItems;
	this.setNavEvents = maps_setNavEvents;
	this.setZoomAction = maps_setZoomAction;
	this.doThumbnailPagination = maps_doThumbnailPagination;
	this.setThumbnailAction = maps_setThumbnailAction;
	this.setThumbnails = maps_setThumbnails;
	this.resetViewer = maps_resetViewer;
	this.configureMapbox = maps_configureMapbox;
	this.setTouchAnimation = maps_setTouchAnimation;
	this.openBuilding = maps_openBuilding;
	this.touchZoom = maps_touchZoom;
	this.renderLocationMenu = maps_renderLocationMenu;
	this.renderCategoryMenu = maps_renderCategoryMenu;
	this.setHotspotAction = maps_setHotspotAction;
	this.paginateMenu = maps_paginateMenu;
	this.setSecondaryNavEvents = maps_setSecondaryNavEvents;
	this.doPopup = maps_doPopup;
	this.center = maps_center;
	this.setLegend = maps_setLegend;
	this.setGMap = maps_setGMap;
	this.updateGMapLink = maps_updateGMapLink;
	this.createGMapLink = maps_createGMapLink;
	this.selectLocationMenuItem = maps_selectLocationMenuItem;
	this.sortMenuItems = maps_sortMenuItems;
	this.updatePrintLink = maps_updatePrintLink;
	this.showMap = maps_showMap;
	this.findNearestBuilding = maps_findNearestBuilding;
	this.setCanvas = maps_setCanvas;
	this.doSearch = maps_doSearch;
	
	this.__construct = function(o){
		var obj = this;
		obj.parent = o;
		obj.viewState = obj.parent.defaults.view;
		obj.mapsState = obj.parent.defaults.state;
		obj.mapbox = '#viewbox_' + obj.viewState;
		
		obj.renderCategoryMenu();
		obj.setTouchAnimation();
		obj.setNavEvents();
		obj.setSecondaryNavEvents();	
		obj.setHotspotAction();
		obj.setThumbnailAction();
		if( obj.parent.mobile == false ){
			//do not allow zooming on mobile.
			obj.setZoomAction();
		}	
		if( obj.parent.mobile == true) {
			obj.thumbnails.height = '51px';
			obj.thumbnails.width = '80px';
		}
		obj.showMap();
		
		if(window.location.search.indexOf('q=') != -1){
			//do a search parameter lookup:
			var term = decodeURIComponent(window.location.search.substring(3)); //assume this is the only parameter
			term = term.replace(/\+/g, ' ');
			$(obj.navigation.locations+' .search .input').val(term);
			$("#loc-search").trigger(obj.clickType.end);
			$(obj.navigation.locations+' .search').submit();
		}
	}	
}

/* #####################################################
 * ############# Hotspot/Building Controls #############
 * #####################################################
 */

function maps_setHotspotAction(){
	var obj = this;

	$(obj.hotspot).removeAttr('title');
	
	$(obj.hotspot).live(obj.clickType.end, function(e) { 
		if(obj.moving == false){	
			//e.clientX = eval(obj.clickType.x);
			//e.clientY = eval(obj.clickType.y);
	
			obj.parent.buildings.active = $(obj.parent.buildings.xml).find(obj.parent.buildingsConfiguration.node+"["+obj.parent.buildingsConfiguration.indexAttr+"='"+$(this).attr(obj.parent.buildingsConfiguration.indexAttr)+"']:first");
			obj.openBuilding();
			obj.selectLocationMenuItem();
		}	
	});
	
	if(obj.parent.mobile == false){
		//allow hovering to produce the popup if not on a mobile device
		$(obj.hotspot).bind("mouseenter", function(e){
			obj.doPopup($(this).attr(obj.parent.buildingsConfiguration.indexAttr), e);
			
			/*
			 * This is a test of canvas/image map connections. It works folks. The campus maps aren't really the right 
			 * place to make use of this unless we built the entire thing in canvas, or turned all of the hotspots into 
			 * canvas items.
			 */
			//obj.setCanvas(this);
		});
	}	

}

function maps_doPopup(number, event){
	var obj = this;
	
	$('.popup').remove();
	var bldg = $(obj.parent.buildings.xml).find(obj.parent.buildingsConfiguration.node+"["+obj.parent.buildingsConfiguration.indexAttr+"='"+number+"']:first");
	
	if(obj.parent.mobile == false){
		if(event.type != 'mouseenter'){
			obj.parent.buildings.active = bldg;
		}	
	}	
	obj.center(bldg);
	
	var title =  bldg.children("title").text();
	
	$('.current-map-layer').append('<div class="popup" style="top: '+obj.center.y+'px; left: '+obj.center.x+'px;"><div class="hotspot button" number="'+number+'"></div><div class="name">'+title+'</div></div>');
	
	if(obj.viewState == 'maps'){
		var inner = '<div class="tiny more"><span>Read more via the tour</span></div>';
		if(obj.parent.mobile == false){
			inner += '<div class="tiny url"><span>Get building link</span></div>';
		}
		inner +='<div class="tiny google"><span>View in Google Maps</span></div>';
		
		$('.popup').append(inner);
		
		$('.popup .tiny.more').bind(obj.clickType.end, function(){
			$(obj.navigation.main+" ul li[action=tour]").trigger(obj.clickType.end);
			obj.parent.buildings.active = bldg;
			
			setTimeout(function(){
				obj.openBuilding();
			}, 1000);
		});
		
		$('.popup .tiny.url').bind(obj.clickType.end, function(){
			$('body').append('<div class="flyout"><div class="background"></div><div class="content"><div class="inner">Copy this link and paste where needed<br/><input size="50" type="text" value="'+obj.parent.domain+'?bldg='+number+'" /></div></div><div class="close">Close - X</div></div>');
					
			$('.flyout').slideDown(300);
			
			$('.flyout .close').bind(obj.clickType.end, function(){
				$('.flyout').slideUp(200, function(){
					$(this).remove();
				});
			});
		});
		
		$('.popup .tiny.google').bind(obj.clickType.end, function(){
			obj.parent.buildings.active = bldg;
			var url = obj.createGMapLink();
			window.location = url;
		});
		
		
	}	
	setTimeout(function(){
		$(".popup .name").show(400, function(){
			$('.popup .tiny').fadeIn(900);
		});
	},600);
	
}

function maps_setCanvas(o){
	/*
	 * Note: width and height must be set as attributes of the canvas object, not inline styles.
	 * Inline style width/height will stretch the object.
	 */
	var obj = this;
	var start_x = obj.center.x - 50;
    var start_y = obj.center.y - 50;
    
	if($("#hotspot_canvas_"+obj.zoom.level+'_'+$(o).attr('number')).length == 0){
		$('.current-map-layer').append('<canvas style="position: absolute; top: '+start_y+'px; left: '+start_x+'px; background-color: #990000; z-index: 100; opacity: 0.8" id="hotspot_canvas_'+obj.zoom.level+'_'+$(o).attr('number')+'" style="z-index: 100"></canvas>');
	}	
	var coords = $(o).attr('coords');
	var coordsArr = coords.split(','); 
	
    
	
	//$('.current-map-layer').append('<canvas style="position: absolute; top: '+start_y+'px; left: '+start_x+'px; background-color: #990000; z-index: 100; opacity: 0.8" id="hotspot_canvas" style="z-index: 100"></canvas>');
	var canvas = document.getElementById("hotspot_canvas_"+obj.zoom.level+'_'+$(o).attr('number'));
	var ctx = canvas.getContext('2d');
    
	ctx.beginPath();
	ctx.moveTo(start_x,start_y);
	for(var n=2;n<coordsArr.length-1;n+=2){
		var x = parseInt(jQuery.trim(coordsArr[n])) - start_x;
		var y = parseInt(jQuery.trim(coordsArr[n+1])) - start_y;
		ctx.lineTo(x,y);
		
	}	
	ctx.fill();
	
	setTimeout(function(){
		$("#hotspot_canvas_"+obj.zoom.level+'_'+$(o).attr('number')).fadeOut(500, function(){$(this).remove()});
	},3000);
}


function maps_openBuilding(){ 
	var obj = this;
	
	//scroll to the top (mostly here for mobile since menu is under the map
	if(obj.parent.mobile != false){
		window.scrollTo(0,110);
	}
	obj.center();

	//zoom to the clicked building				
	if(obj.parent.mobile == false){
		$(obj.imageLevels+obj.zoom.level+'_'+obj.viewState).animate({left: obj.center.x, top: obj.center.y}, 700);		
		obj.zoom.level = 2;
	}	
	
	//google map link
	obj.setGMap();
	obj.updateGMapLink();
	
	//Virtual Tour only:
	if(obj.viewState == 'tour'){
		//clear previous thumbnails
		$(obj.thumbnails.id).children().html('');
		
		//update the content box with new summary
		
		$(obj.selectedAreaContent).html('<h4>'+obj.parent.buildings.active.children("title:first").text()+'</h4>');
		
		//paginate the summary text: (need a better way to do word flow)
		var text = obj.parent.buildings.active.find("summary[type='standard']").text();
		$(obj.selectedAreaContent).append('<p class="tiny">'+text+'</p>');
		
		//Sets initial picturebox-main image (matches the tour)
		var start_node = obj.parent.buildings.active.find('media').children().filter('[type='+obj.viewState+']');
		$(obj.selectedAreaImage).children('img').attr('src',obj.parent.domain+start_node.attr('url'));  
		
		//update the thumbnail image viewer with the new building images 
		obj.setThumbnails();
		$(obj.zoomControl.parent).hide();
		
		if(obj.parent.mobile == false){
			$(obj.mapbox).animate({height: obj.viewport.heightSmall , width: obj.viewport.widthSmall}, 750, 
					function() {
						$(obj.thumbnails.id).children().fadeIn(500);
						$(obj.selectedAreaContent).children().fadeIn(500);
						$("#summary .content").slideDown(500);
						$(obj.selectedAreaImage).fadeIn(500,
							function (){
								obj.configureMapbox();
							}						
						);
					}
				);
		}
		else{
			$(obj.mapbox).animate({height: '0px'}, 750, function() {
				//$('#content-right, #tour, #tour-wrapper').animate({height : '400px'}, 500);
				$(obj.selectedAreaContent).slideDown(500);
				$(obj.selectedAreaImage).fadeIn(500, function(){
					$(obj.thumbnails.id).children().fadeIn(500);
					obj.configureMapbox();
				});
			});	
		}
	}	
	else{
		$(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').trigger(obj.clickType.end);
		obj.configureMapbox();
	}	
	
}

/*
 * #################################################
 * ############# Google Maps Functions #############
 * #################################################
 */

function maps_setGMap(){
	var obj = this;
	var x = this.parent.buildings.active.find('mapCoordinates x[type="geolocation"]').text();
	var y = this.parent.buildings.active.find('mapCoordinates y[type="geolocation"]').text();
	var z = obj.gmap.zoomFactor + obj.zoom.level; 
	
	/* Static Map Images*/
	var url = obj.gmap.url+'&center='+x+','+y+'&markers=color:red|label:|'+x+','+y+'&zoom='+z;
	$(obj.gmap.id).html(obj.gmap.html);	
	$(obj.gmap.id+' img:first').attr('src', url);

	
/*non-working live GAPIcode
	var geocoder = new google.maps.Geocoder();
	var gmap_center = new google.maps.LatLng(x, y);
	var gmap_options = {
		zoom: z,
		center: gmap_center,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	var gmap = new google.maps.Map(document.getElementById("viewbox_maps"), obj.gmapOptions);
	
	var marker = new google.maps.Marker({
		position: gmap_center,
		map: gmap
	});
*/	
}

function maps_createGMapLink(){
	var obj = this;
	var x = this.parent.buildings.active.find('mapCoordinates x[type="geolocation"]').text();
	var y = this.parent.buildings.active.find('mapCoordinates y[type="geolocation"]').text();
	var z = obj.gmap.zoomFactor + obj.zoom.level; 
	var url = obj.gmap.appUrl+'&q='+x+','+y+'&ll='+x+','+y+'&z='+z;
	return url;
}

function maps_updateGMapLink(){
	var obj = this;
	var url = obj.createGMapLink();
	$("#google").html('<a href="'+url+'" target="_blank"><span>View in Google Maps</span></a>');
	$("#google").show();

}

/*
 * #########################################
 * ############# Zoom Controls #############
 * #########################################
 */

function maps_setZoomAction(){	
	var obj = this;
	//------------------------Mousewheel Zooming------------------------//
	$('#viewbox_tour, #viewbox_maps').bind('mousewheel', function(event, delta) {
		if (delta > 0) {
			obj.zoom.level++;
			if(obj.zoom.level > obj.zoom.max) {
				obj.zoom.level = obj.zoom.max;
			}
			$(obj.zoomControl.slider).css('left', $(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').position().left);
			$(this).mapbox("zoomTo", obj.zoom.level);
		}
		
		if (delta < 0) {
			obj.zoom.level--;
			if(obj.zoom.level < 0) {
				obj.zoom.level = 0;
			}		
			$(obj.zoomControl.slider).css('left', $(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').position().left);
			$(this).mapbox("zoomTo", obj.zoom.level);
		}
	});
	
	//------------------------Control Zooming------------------------//
	$(obj.zoomControl.levels).bind(obj.clickType.end, function(e){
		obj.zoom.level = parseInt($(this).attr('level'));
		$(obj.zoomControl.slider).animate({'left' : $(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').position().left}, 300, function(){
			$(obj.mapbox).mapbox("zoomTo", obj.zoom.level);
		});	
	});
	$(obj.zoomControl.plus).bind(obj.clickType.end, function(e){		
		obj.zoom.level = obj.zoom.max;
		$(obj.zoomControl.slider).animate({'left' : $(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').position().left}, 500, function(){
			$(obj.mapbox).mapbox("zoomTo", obj.zoom.level);
		});	
	});
	$(obj.zoomControl.minus).bind(obj.clickType.end, function(e){
		obj.zoom.level = 0;
		$(obj.zoomControl.slider).animate({'left' : $(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').position().left}, 500, function(){
			$(obj.mapbox).mapbox("zoomTo", obj.zoom.level);
		});	
	});
	
	/*//slider
	var currentY;
	var difference;
	var pos;
	
	$(obj.zoomControl.parent+','+obj.zoomControl.slider).bind(obj.clickType.start,function(){
		return false;
	});
	
	$(obj.zoomControl.slider).bind(obj.clickType.start, function(e){
		e.clientY = eval(obj.clickType.y);
		currentY = e.clientY;
		obj.zoomControl.sliderActive = true;
	});	
	$(obj.zoomControl.parent+','+obj.zoomControl.slider).bind(obj.clickType.move, function(e){
		e.clientY = eval(obj.clickType.y);
		
		if(obj.zoomControl.sliderActive == true){
			difference = currentY - e.clientY;	
			pos = $(obj.zoomControl.slider).position().top - difference;
			if( (pos >= $(obj.zoomControl.levels).filter(':first').position().top - 10) && (pos < $(obj.zoomControl.levels).filter(':last').position().top - 10) ){
				$(obj.zoomControl.slider).css('top', pos );
				currentY = e.clientY;
			}	
			else{
				currentY = e.clientY;
				obj.zoomControl.sliderActive = false;
			}			
		}	
	});	
	
	$(obj.zoomControl.parent+','+obj.zoomControl.slider).bind(obj.clickType.end, function(e){
		obj.zoomControl.sliderActive = false;
		$(obj.zoomControl.levels).each(function(){
			if( (pos < $(this).position().top + 48) && (pos > $(this).prev().position().top + 48) ){
				$(obj.zoomControl.slider).animate({'top' : $(this).position().top-10}, 200, function(){
					obj.zoom.level = parseInt($(this).attr('level'));
					$(obj.mapbox).mapbox("zoomTo", obj.zoom.level);
					//return false;
				});	
			}
		});
	});
	
	$(document).bind(obj.clickType.end, function(e){
		//currentY = '';
		obj.zoomControl.sliderActive = false;
	});
		*/
	
}

function maps_findNearestBuilding(){
	/*
	 * still a bit buggy. not ready for production.
	 */
	var obj = this;
	//center value for the map image:
	var y = Math.abs($(obj.mapbox+' .current-map-layer').position().top) + ($(obj.mapbox).height()/2);
	var x = Math.abs($(obj.mapbox+' .current-map-layer').position().left) + ($(obj.mapbox).width()/2);
	
	var closest = 0;//$(obj.mapbox+' .current-map-layer').position().top;
	var contenders = new Array();
	var closestNode;
	var val;
	
	var factor = eval('obj.multipliers.'+obj.viewState+'[obj.zoom.level]');
	
	$(obj.parent.buildings.xml).find('mapCoordinates').each(function(){
		val = factor*parseFloat($(this).children('y[type="'+obj.viewState+'"]').text());
		//go through the y values and get contenders
		if (Math.abs(y-val) < Math.abs(y-closest)){
			closest = val;
			contenders.push(this);
		}	
	});
	
	closest = 0;
	for(var n=0; n<contenders.length; n++){
		//go through x values to find the closest node
		val = factor*parseFloat($(contenders[n]).children('x[type="'+obj.viewState+'"]').text());
		
		if (Math.abs(x-val) < Math.abs(x-closest)){
			closest = val;
			closestNode = $(contenders[n]).parent();
		}	
	}

}

/* #####################################################
 * ############# General Map Configuration #############
 * #####################################################
 */
function maps_showMap(){
	var obj = this;
	$(obj.navigation.main+" ul li[action="+obj.parent.defaults.view+"]").trigger(obj.clickType.end, [true]);
}

function maps_resetViewer(){
	var obj = this;
	//resets the map for browsing
	$(obj.gmap.id).html('');
	$(obj.navigation.maps).children(':first').trigger(obj.clickType.end);
	$(obj.selectedAreaImage+','+obj.thumbnails.id).fadeOut();
	$(obj.selectedAreaContent).slideUp();
	$(obj.mapbox).animate({height: obj.viewport.heightStandard , width: obj.viewport.widthStandard}, 500,
			function() {
				if(obj.parent.mobile == false){
					$(obj.navigation.zoom).css("z-index", "2").fadeIn(500, function(){
						$(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').trigger(obj.clickType.end);
					});
				}	
				
			}
		);
}

function maps_center(bldg){
	var obj = this;
	
	if(!(bldg)){
		bldg = obj.parent.buildings.active;
	}	
	//use the active building coordinates for the appropriate map
	obj.coordinates.x = bldg.find('mapCoordinates x[type="'+obj.viewState+'"]').text();
	obj.coordinates.y = bldg.find('mapCoordinates y[type="'+obj.viewState+'"]').text();
	
	//X & Y coordinates for panning animation
	var factor = eval('obj.multipliers.'+obj.viewState+'[obj.zoom.level]');
	
	obj.center.x = obj.coordinates.x*parseFloat(factor);
	obj.center.y = obj.coordinates.y*parseFloat(factor); 
}

function maps_configureMapbox(){
	var obj = this;	
	
	$(".popup").remove();
	obj.doPopup(obj.parent.buildings.active.attr(obj.parent.buildingsConfiguration.indexAttr), false);
	//Configure Mapbox settings:
	$(obj.mapbox).mapbox({layerSplit: 1});
	$(obj.mapbox).mapbox("zoomTo", obj.zoom.level);
	$(obj.mapbox).mapbox("center", {x:obj.center.x, y:obj.center.y});
}

/* ##################################################
 * ############# General Map Navigation #############
 * ##################################################
 */
function maps_setSearch(){
	var obj = this;
	
	$("#loc-search").bind(obj.clickType.end, function(e){
		if($("#loc-search").is('.on')){
			$("#locations form.search").slideUp();
			$(this).removeClass('on');
		}
		else{
			$("#loc-nav").trigger(obj.clickType.end);
			$("#locations form.search").slideDown();
			$(this).addClass('on');
		}
		
		if($("#loc-nav").is('.on')){
			e.stopPropagation();
		}	
	});
	
	$("#locations form.search").submit(function(){
		obj.doSearch($("#vtour form.search .input").val());
		$("#locations form.search .input").trigger('blur');
		return false;
	});
	
	$("#locations form.search .input").bind('focus', function(){
		if($(this).val() == 'Search locations'){
			$(this).val('');
		}
	});	
	
	/*if(obj.parent.mobile == false){
		//do a lookahead if not mobile
		//$("#loc-nav").trigger(obj.clickType.end);
		obj.checkLookupItems();
	}	*/
}
function maps_checkLookupItems(){
	var obj = this;
	var needle = $("#vtour form.search .input").val();
	/*
	 * This if clause keeps the rewriting portion of the script from occuring if the 
	 * search input hasn't changed since the last check.
	 */
	if (cli_timeout_value != needle){
		cli_timeout_value = needle;
		obj.doSearch(needle);
	}		
	cli_timeout = setTimeout(function(){
		obj.checkLookupItems();
	},500);	
}

function maps_doSearch(needle){
	var obj = this;
	//escape apostrophes
	needle = needle.replace(/'/g,"\'");
	
	//Replace banned Characters:
	needle = needle.replace(/"/g,"");
	
	//make everything lowercase
	needle = needle.toLowerCase();	
	
	if((needle != '') || (needle != 'Search locations')) {
		var showThese = $(obj.parent.buildings.xml).find(obj.parent.buildingsConfiguration.node).filter(function(index){
			var haystack = $('title',this).text().toLowerCase();
			$('summary', this).each(function(){
				haystack += ' '+$(this).text().toLowerCase();
			});	
			$('category', this).each(function(){
				haystack += ' '+$(this).text().toLowerCase();
			});	
			if(haystack.indexOf(needle) != -1){
				return this;
			}
		});
		obj.renderLocationMenu(showThese);
	}	
	else{
		obj.renderLocationMenu();
	}
	
	return false;
}

function maps_setNavEvents(){
	var obj = this;
	//-------------------------Vtour-Nav-------------------------//
	var mainNav = $(obj.navigation.main+" ul li")
		
	mainNav.bind(obj.clickType.end, function(e, initialRun){
		//if(obj.parent.mobile == false){
			$(obj.navigation.main+" ul li.vtour-button-white").removeClass("vtour-button-white").addClass("vtour-button-blue");
			$(this).removeClass("vtour-button-blue").addClass("vtour-button-white");
		//}
		//change the map displayed
		$(obj.viewport.id).hide();
		$('#'+$(this).attr('action')).show();
		obj.viewState = $(this).attr('action');
		obj.mapbox = '#viewbox_'+obj.viewState;
		
		obj.setLegend();		
		obj.configureMapbox();
		obj.resetViewer();
		
		if(initialRun){
			if(obj.viewState == 'maps'){
				$(obj.navigation.maps+" > *[action="+obj.parent.defaults.state+"]").trigger(obj.clickType.end);
			}
			if(obj.parent.defaults.showPopup == true){
				obj.doPopup(obj.parent.defaults.building, false);
			}
			
		}
		
		
	});
	
	//-------------------------sidebar-Nav-------------------------//
	$(obj.navigation.secondary).children('.listbox-nav-button').bind(obj.clickType.end, function(e){
		//show the correct content:
		var find = $(this).text();
		find = find.toLowerCase();
		find = jQuery.trim(find);
		
		if(find == 'locations'){
			obj.renderLocationMenu();
			$('#locations form').hide();
			$("#loc-search").removeClass('on');
			$(obj.navigation.locations).children('.title:first').empty();
				
		}	
		$(obj.navigation.secondary_content).children().hide();
		
		var content = $(obj.navigation.secondary_content).find("#"+find);
		content.css('width','100%');
		content.fadeIn();
		
		$(obj.navigation.secondary).children().removeClass('on');
		$(this).addClass('on');
		
	});
	
	obj.setSearch();
	
	//-------------------------maps-Nav-------------------------//
	$(obj.navigation.maps).children().bind(obj.clickType.end, function(e){
		$(obj.gmap.id).hide();
		
		if(obj.parent.mobile == false){
			$(obj.zoomControl.parent).show();
		}
		obj.mapsState = $(this).attr('action');
		var allActions = new Array();
		$(obj.navigation.maps).children().each(function(){
			allActions.push($(this).attr('action'));
		});	
		
		if(obj.mapsState != 'google'){
			$(obj.gmap.id).html('');
			var images = $(obj.mapbox).find('img');
			images.each(function(){
				for(var i=0; i<allActions.length; i++){
					var src = $(this).attr('src');
					
					if(src.indexOf(allActions[i]) != -1){
						src = src.replace(allActions[i], obj.mapsState);
						$(this).attr('src',src);
					}	
				}
			});
		}
		else{
			obj.setGMap();
			obj.updateGMapLink();
			$(obj.zoomControl.parent).hide();
			$(obj.gmap.id).show();
		}
		obj.setLegend();
		$(this).parent().children().removeClass('on');
		$(this).addClass('on');
		
	});
	
	
	//if mobile, remove the "Satellite" map choice for more room.
	/*if(obj.parent.mobile != false){
		$("#maps-nav li:last").remove();
	}*/
}

function maps_updatePrintLink(){
	var obj = this;
	$("#download").hide();
	
	if( (obj.viewState == 'maps') && (obj.mapsState != 'google') ){
		$("#download").html('<a href="'+obj.parent.domain+'print/'+obj.mapsState+'.pdf" target="_blank"><span>Download Printable PDF</span></a>');
		$("#download").show();
	}
	
}

function maps_setLegend(){
	var obj = this;
	$("#legend").hide();
	if( (typeof(obj.mapsState) != 'undefined') && (obj.mapsState != 'undefined') ){
		if( (obj.viewState == 'maps') && (obj.mapsState != 'google') ){
			$("#legend").html('<div class="title">Legend</div><img src="'+obj.parent.domain+'images/legends/'+obj.mapsState+'.gif" alt="Map Legend"/>');
			$("#legend").show();
		}
	}	
	obj.updatePrintLink();
}

function maps_setSecondaryNavEvents(){
	var obj = this;
	
	var items = obj.navigation.categories+' .content .item, '+obj.navigation.locations+' .content .item';
	
	$(items).live(obj.clickType.start, function(e){
		$(items).removeClass('hover');
		$(this).addClass('hover');
	});	
	
	$(obj.navigation.categories+' .content .item').live(obj.clickType.end, function(e){
		$(this).removeClass('hover');
		var catStr = $(this).text();

		$(obj.navigation.categories).animate({'width':'0'}, 400, function(){
			$(this).hide();
			
			var showThese = $(obj.parent.buildings.xml).find(obj.parent.buildingsConfiguration.node).filter(function(index){
				 return $('categories > category:contains('+catStr+')', this).length > 0;
			});
			obj.renderLocationMenu(showThese);
			$(obj.navigation.secondary).children().removeClass('on');
			$("#loc-nav").addClass('on');
			
		
			$(obj.navigation.locations).children('.title:first').text(catStr);
			
						
		});	
		
	})
	
	$(obj.navigation.locations+' .content .item').live(obj.clickType.end, function(e){
		obj.parent.buildings.active = $(obj.parent.buildings.xml).find(obj.parent.buildingsConfiguration.node+"["+obj.parent.buildingsConfiguration.indexAttr+"='"+$(this).attr(obj.parent.buildingsConfiguration.indexAttr)+"']:first");
		$("#content-right").show();
			
		obj.openBuilding();
		obj.doPopup($(this).attr(obj.parent.buildingsConfiguration.indexAttr), e);
	});
}


function maps_renderCategoryMenu(){
	var obj = this;
	var menu = $(obj.navigation.categories).children('.content:first');
	menu.empty();

	var categories = $(obj.parent.buildings.xml).find(obj.parent.buildingsConfiguration.node+' > categories > category');
	categories = obj.sortMenuItems(categories);
	
	categories.each(function(){
		if(menu.html().indexOf('>'+$(this).text()+'<') == -1){
			menu.append('<div class="item"><p>'+$(this).text()+'</p></div>');
		}	
	});
	if(typeof(assetsUrl) == 'undefined'){
		//KP2
		obj.paginateMenu($(obj.navigation.categories), obj.parent.dimensions.categoryMenuHeight);
	}
	
}

function maps_renderLocationMenu(set){
	var obj = this;
	
	if(!(set)){
		set = $(obj.parent.buildings.xml);
	}
	var menu = $(obj.navigation.locations+' .content:first');
	
	menu.empty();
	
	var titles = set.find('title');
	titles = obj.sortMenuItems(titles);
	titles.each(function(){
		menu.append('<div class="item" number="'+$(this).parent().attr(obj.parent.buildingsConfiguration.indexAttr)+'"><p>'+$(this).text()+'</p></div>');
	});
	
	$(obj.navigation.locations).show();
	obj.paginateMenu($(obj.navigation.locations), obj.parent.dimensions.locationsMenuHeight);
	
	var activeItem = menu.find('.item['+obj.parent.buildingsConfiguration.indexAttr+'="'+obj.parent.buildings.active.attr(obj.parent.buildingsConfiguration.indexAttr)+'"]');
	if(activeItem.length > 0){
		activeItem.addClass('hover');

		if(typeof(assetsUrl) == 'undefined'){
			//KP2
		
			var pageIndex = activeItem.parent().index();
			$(obj.navigation.locations).find('.paginationControls .controls span').eq(pageIndex).trigger('click');
		}	
	}	

}

function maps_sortMenuItems(set){
	set.sort(function(a, b){
		var compA = $(a).text();
		var compB = $(b).text();
		return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
	});
	return set;
}

function maps_selectLocationMenuItem(){
	var obj = this;
	$(obj.navigation.secondary).children(':last').trigger(obj.clickType.end);
}

function maps_paginateMenu(o,h){
	var obj = this;
	
	if(typeof(assetsUrl) == 'undefined'){
		//Paginate this:
		if(obj.parent.mobile == false){
			o.find('.paginationControls').remove();
			
			var pages = new CollapsedContent();
			pages.paginate.container = o.find(".content");
			pages.paginate.enabled = true;
			pages.paginate.includeNumbers = true;
			pages.paginate.height = h;
			pages.paginate.forcePageHeights = h+"px";
			pages.paginate.showParent = true;
			pages.paginate.controlParent = o;
			pages.setPagination();
		}	
	}
	else{
		//KP3
		o.find('#atoz').remove();
		
		var chars = new Array();
		var unique = new Array();
		
		if(obj.parent.mobile == false){
			o.find('.content .item').each(function(){
				//get all of the first characters:
				var char = $(this).text().substring(0,1).toLowerCase();
				chars.push(char);
			});
			
			chars.sort();
			for(var n=0;n<chars.length; n++){
				if(chars[n] != chars[n+1]){
					unique.push(chars[n]);
				}
			}
			//create the atoz:
			o.children(':first').after('<div class="atoz" id="atoz">'+
					'<span>Show items starting with:</span>'+
					'<div class="controls"></div>'+
					'</div>');
			var parent = o.find('#atoz .controls');
			
			for(var n=0;n<unique.length; n++){
				parent.append('<div class="item">'+unique[n]+'</div>');
			}
			parent.append('<div class="item">All</div><div class="clear"></div>');
			
			//change styles:
			o.find('.content').css({
				overflow: 'auto',
				height : '190px',
				width: '100%',
				margin: '10px 0px'
			});
			
			o.find('.content .item').hide();
			
			//set atoz controls:
			o.find('#atoz .controls .item').click(function(){
				o.find('#atoz .controls .item').removeClass('on');
				$(this).addClass('on');
				
				var value = $(this).text();
				if(value != 'All'){
					o.find('.content .item').hide();
					o.find('.content .item').filter(function(){
						return $(this).text().substring(0,1).toLowerCase() == value;
					}).fadeIn();
				}
				else{
					o.find('.item').fadeIn();
				}
			});
			
			//click the ALL button:
			o.find('#atoz .controls .item:last').trigger('click');
		}	
		
	}
	
}

/* ####################################################
 * ############# Thumbnails/Image Viewing #############
 * ####################################################
 */		
function maps_setThumbnails(){
	var obj = this;
	
	obj.thumbnails.xmlSet = obj.parent.buildings.active.find('media').children().filter(':not([type="'+obj.viewState+'"])');
	
	$(obj.thumbnails.id).children().remove();
	$(obj.thumbnails.containers).unbind(obj.clickType.end);
	
	if(obj.parent.mobile != false){
		obj.thumbnails.displayMax = obj.thumbnails.xmlSet.length;
	}
	
	for(var n=0; n < obj.thumbnails.displayMax; n++){
		var node = obj.thumbnails.xmlSet.eq(n);
		if(node.length > 0){
			$(obj.thumbnails.id).append('<div class="picturebox-thumb"><img number="'+n+'" src="'+obj.parent.domain+node.attr("url") + '" alt="" /></div>');
		}	
	}
	//resize all of the thumbnail images:
	$(obj.thumbnails.containers).children('img').height(obj.thumbnails.height).width(obj.thumbnails.width);

	if(obj.parent.mobile == false){
	//if there are more images than can be displayed replace the last one with the next button and add the click action
		if(obj.thumbnails.xmlSet.length > obj.thumbnails.displayMax){	
			$(obj.thumbnails.containers).filter(':last').remove();
			
				$(obj.thumbnails.id).append('<div class="button"><img class="next" src="'+obj.thumbnails.nextButtonUrl+'" alt="Next Items" /></div>');
				$(obj.thumbnails.id).children(".button").bind(obj.clickType.end, function(e){
					obj.doThumbnailPagination();	
				});
		}	
		$(obj.thumbnails.id).show();
	}
	else{
		//mobile: do the thumbnails as a slider:
		$(obj.thumbnails.id).show();
		var w = 0;
		$(obj.thumbnails.id).children().each(function(){
			w += $(this).outerWidth(true);
		});
		
		//test:
		//w = obj.thumbnails.xmlSet.length*90;
		
		
		$(obj.thumbnails.id).children().wrapAll('<div class="slideWrap"></div>');
		$(obj.thumbnails.id).append('<div class="indicator"></div><div class="shadow left"></div><div class="shadow right"></div>');
		
		
		var activeEl = $(obj.thumbnails.id).find(".slideWrap .picturebox-thumb:first");
		
		
		$(obj.thumbnails.id).find(".slideWrap").css({
			position: 'absolute',
			top: '6px',
			left: '0',
			width: w+'px'
				
		});
		
		var start_x;
		$(obj.thumbnails.id).find(".slideWrap .picturebox-thumb").bind(obj.clickType.start, function(e){
			e.clientX = eval(obj.clickType.x);
			start_x = e.clientX;
		});	
	
		$(obj.thumbnails.id).find(".slideWrap .picturebox-thumb").bind(obj.clickType.end, function(e){
			e.clientX = eval(obj.clickType.x);
			
			if(start_x == e.clientX){
				$('body').unbind(obj.clickType.end);
				$(obj.thumbnails.id).unbind(obj.clickType.move);
				
				activeEl = $(this);
				$(obj.thumbnails.id).children('.slideWrap').animate({
					'left': -1*(activeEl.position().left - ($(obj.thumbnails.id).width()/2) + (activeEl.outerWidth(true)/2))
				}, 500);
			}	
			
			
			//return false;
		});
		
		$(obj.thumbnails.id).bind(obj.clickType.start, function(e){	
			obj.slideMenu($(this), e);
		});
		
		//set the slideMenu function declaration from jquery-mobile-ui.js:
		obj.slideMenu = mu_slideMenu;
		
	}

}

function maps_setThumbnailAction(){
	var obj = this;
			
	$(obj.thumbnails.containers).live(obj.clickType.end, function(e){			
	 	//Toggle the main image:
		$(obj.thumbnails.containers).removeClass("active");
		$(this).addClass("active");
		$(obj.selectedAreaImage).children('img').attr('src', $(this).children('img:first').attr("src"));
	});
}

function maps_doThumbnailPagination(){
	var obj = this;
	
	$(obj.thumbnails.containers).removeClass('active');
	
	$(obj.thumbnails.containers).find('img').fadeOut(500, function(){
	
		var last = parseInt($(obj.thumbnails.containers).filter(':last').find('img').attr(obj.parent.buildingsConfiguration.indexAttr));
		
		for(var n=0; n<obj.thumbnails.displayMax; n++){
			
			if(last+n > obj.thumbnails.displayMax){
				var nodeValue = n;
			}
			else if (last+n == obj.thumbnails.displayMax){
				var nodeValue = 0;
			}
			else{
				var nodeValue = last + n;
			}
	
			var node = obj.thumbnails.xmlSet.eq(nodeValue);
			$(obj.thumbnails.containers).eq(n).html('<img src="'+obj.parent.domain+node.attr("url") + '" number="'+nodeValue+'" />')
		}
		//resize all of the thumbnail images:
		$(obj.thumbnails.containers).children('img').height(obj.thumbnails.height).width(obj.thumbnails.width);
	});	
}

/* ##########################################
 * ############# Touch Controls #############
 * ##########################################
 */
function maps_setTouchAnimation(){     
	var obj = this;
	//stop native mouse actions (to prevent dragging everywhere)
	$('#viewbox_tour, #viewbox_maps').bind('mousedown',function(){
		return false;
	});	
	
	//pick touch or click
	document.body.setAttribute('ontouchmove','return;');
	if(typeof document.body.ontouchmove == 'function'){
		obj.clickType = {
				start: 'touchstart',
				move: 'touchmove',
				end: 'touchend',
				x: 'event.changedTouches[0].clientX',
				y: 'event.changedTouches[0].clientY'
		}
		obj.touchZoom();
	}	
	else{
		obj.clickType = {
				start: 'mousedown',
				move: 'mousemove',
				end: 'mouseup',
				x: 'e.clientX',
				y: 'e.clientY'
		}		
	}
	
	//configure the button that toggles from buildings to tour map:
	$(obj.selectedAreaImage+' .return').bind(obj.clickType.end, function(){
		obj.resetViewer();
	});
	
	//remove menu classes when the map is moved:
	$('#viewbox_tour, #viewbox_maps').bind(obj.clickType.start, function(){
		$(obj.navigation.locations).find('li').removeClass('hover');
	});	
}
function maps_touchZoom(){
	var obj = this;
	$('#viewbox_tour, #viewbox_maps').bind('mousedown',function(){
		return false;
	});
	
	$('#viewbox_tour, #viewbox_maps').live(obj.clickType.move, function(e){
		obj.moving = true;
	});
	
	$('#viewbox_tour, #viewbox_maps').live(obj.clickType.end, function(e){
		setTimeout(function(){
			obj.moving = false;
		}, 50);
		return false;
	});	
	
	$('#viewbox_tour, #viewbox_maps').live('gesturechange', function(e){
			var img = $('.current-map-layer .mapcontent img:first');
			
			if(event.scale > 1){	
				if(event.scale > 2){
					$(obj.mapbox).trigger('gestureend');
					obj.zoom.level++;
					if(obj.zoom.level > obj.zoom.max){
						obj.zoom.level = obj.zoom.max;
					}
				}
			}	
			else if(event.scale < 1){
				if(event.scale < 0.5){
					$(obj.mapbox).trigger('gestureend');
					obj.zoom.level--;
					if(obj.zoom.level < 0){
						obj.zoom.level = 0;
					}
				}
			}
			return false;
	});
	$('#viewbox_tour, #viewbox_maps').live('gestureend', function(e){
		$(obj.zoomControl.levels+'[level="'+obj.zoom.level+'"]').trigger(obj.clickType.end);	
	});	
	
}


/* ######################################################
 * ###################  Buildings Data  #################
 * ######################################################
 */
function Maps_Buildings(){
	this.parent;

	this.thumbnails = $("#picturebox-thumbnails");
	this.thumbnailsWidth = '119px';
	this.thumbnailsHeight = '76px';
	
	this.active = false; //this is the actively clicked building node from the XML file
	
	this.xml;
	
	var obj = this;
	this.__construct = function(o){
		var obj = this;
		obj.parent = o;
		$.ajax({
			url: obj.parent.buildingsConfiguration.xmlUrl,
			type: "GET",
			success: function(data){
				obj.xml = data;			
				obj.active = $(obj.xml).find(obj.parent.buildingsConfiguration.node+"["+obj.parent.buildingsConfiguration.indexAttr+"="+obj.parent.defaults.building+"]:first"); //set to Boatwright by default;
				obj.parent.controls.__construct(obj.parent);				
			}
		});
	};	
	
}

/* ######################################################
 * ###################  Directory Data  #################
 * ######################################################
 */
function Maps_Directory(){
	return true;
	
	this.parent;
	this.__construct = function(o){
		var obj = this;
		obj.parent = o;
	}	
}
