(function($) {
	function Axis41() {};
	
	$.extend(Axis41.prototype, {
		settings: {
			base_url: '',						/* The Site's base url to be able to make ajax calls and load in dynamic content correctly */
			image_size_timer: null,				/* The timer to size the full screen images when the browser window is being resized. */
			current_active_subnav: null,		/* The currently shown nav item */
			switching_subnav: null,				/* The nav item that is being switched to */
			nav_timer: null,					/* The timer for the nav show/change action, to avoid confusion */
			subnav_timer: null,					/* The timer for hiding the subnavigation so that it doesn’t animate up to soon */
			portfolio_timer: null,				/* The timer for hiding the portfolio buttons */
			portfolioThumnails_timer: null,		/* timer for the scrolling portfolio thumbnails */
			client_portfolio_timer: null,		/* timer for closing the client portfolio */
			first_item_timer: null,				/* timer for the first portfolio item */
			last_item_timer: null,				/* timer for the last portfolio item */
			scroll_api: null,					/* scroll api */
			portfolio_next_link: null,			/* next link on the portfolio */
			portfolio_prev_link: null,			/* prev link on the portfolio */
			current_portfolio_number: null,		/* the index number for the current portfolio item */
			initialPageLoad: true,				/* flag if it is the initial page load or not */
			slideshow: {						/* Settings for the slideshow */
				enabled: false,					/* Inicating whether or not the slideshow is enabled */
				timer: null,					/* Timer for the slideshow */
				delay: 4						/* Seconds indicating the delay to show each image */
			}
		},
		
		loadingBoxTimer: null,
		dataForCurrentSet: { url: null, data: null }, /* The JSON data for the current set of images */
		cachedImages: [], /* The array of image objects that have been cached for the current set */
		cacheImageTimmers: [], /* The array of image cache timmers */
		current_image_data: {}, /* data for the image currently being shown */
		next_image_data: {loaded: false}, /* next image data for caching */
		prev_image_data: {loaded: false}, /* previous image data for caching */
		imageSizes: [
			[800, 600],
			[1024, 576],
			[1024, 768],
			[1280, 720],
			[1280, 800],
			[1280, 960],
			[1280, 1024],
			[1400, 1050],
			[1440, 900],
			[1600, 1200],
			[1680, 1050],
			[1920, 1080],
			[1920, 1200],
			[2560, 1600]
		], /* Image sizes */
		subNavigationShowTimer: null, /* The timer for showing the subnavigation */
		subSubNavigationShowTimer: null, /* The timer for showing the subnavigation of the subnavigation */
		processKeyCommandsTimer: null, /* Timer to process key commands so that pushing the keys a lot doesn’t cause an issue. */
		
		/* Function that gets run on page load to setup all the javascript that the site might need to run */
		init: function (settings) {
			this.settings = jQuery.extend({}, this.settings, settings);
			this.runSetup();
			
			if (window.location.toString().indexOf('portfolio') != -1 && $('.left-col').length < 1) { // only want to do this on portfolio pages
				$(window).resize(function() {
					$.axis41.windowResizeActions();
				});
				
				if (window.location.hash == '') {
					$.axis41.loadPage();
				}
			
				// setup the hashes for ajax calls
				$.historyInit($.axis41.loadPage);
			}
		},
		
		homepageInit: function() {
			this.runSetup();
			
			// Homepage housekeeping
			$('#portfolio_navigation.closed h1').css('background', 'transparent');
			$('#prev_next_con, #portfolio-prev, #portfolio-next, #thumb_group_prev, #thumb_group_next, #thumbnail_con').remove();
			
			if (window.location.hash != '') {
				window.location.hash = "";
			}
			
			$.axis41.settings.slideshow.enabled = true;
			$.axis41.loadPage(null, $.axis41.settings.base_url + '/portfolio/slideshow');
			
			$(window).resize(function() {				
				clearTimeout($.axis41.settings.slideshow.timer);
				$.axis41.windowResizeActions();
			});
		},
		
		/* The main setup function call */
		runSetup: function() {
			this.setupNav();
			this.setupPortfolioNavigation();
			this.setupPortfolioThumbnails();
			this.setupClientList();
			this.setBodyHeight();
			this.setUpCollapseBoxes();
			this.setupMapPopup();
		},
		
		/* The actions for the Slideshow */
		runSlideshow: function() {
			clearTimeout($.axis41.settings.slideshow.timer);
			
			$.axis41.settings.slideshow.timer = setTimeout(function() {
				if ($.axis41.findCurrentDataById($.axis41.current_image_data.id, true) != parseInt($.axis41.dataForCurrentSet.data.length-1)) {
					var nextItem = $.axis41.dataForCurrentSet.data[parseInt($.axis41.findCurrentDataById($.axis41.current_image_data.id, true)+1)];
					$.axis41.loadPage('i' + nextItem.id, $.axis41.dataForCurrentSet.url);
				} else {
					$.axis41.dataForCurrentSet.url = null;
					$.axis41.dataForCurrentSet.data = null;
					$.axis41.loadPage(null, $.axis41.settings.base_url + '/portfolio/slideshow?fullset');
				}
			}, $.axis41.settings.slideshow.delay*1000);
		},
		
		/* scrolls portfolio thumbnails so the current one is in view */
		scrollPortfolioThumbnails: function() {
			if ($.axis41.settings.scroll_api) {
				// calculate how many pages we need to scroll
				var pages = Math.floor($.axis41.settings.current_portfolio_number / 10);
				
				if (pages > 0) {
					$.axis41.settings.scroll_api.setPage(pages);
				}
			}
		},
		
		/* Actions that get run when the window resizes */
		windowResizeActions: function() {		
			// Show the loading indicator
			$.axis41.addLoadingBox();
			
			// Time out for the resize actions so that we wait for the user to stop resizing for a bit before running the actions
			clearTimeout($.axis41.settings.image_size_timer);
			$.axis41.settings.image_size_timer = setTimeout(function() {
				$.axis41.windowResizeTimerActions();
			}, 500);
		},
		
		/* resize timer actions */
		windowResizeTimerActions: function() {
			var is_logo = $('#page_canvas').hasClass('logo');
			var is_website = $('#page_canvas').hasClass('website');
			$.axis41.changePortfolioImage($('#current-image').attr('src'), is_logo, is_website);
			
			$.axis41.setBodyHeight();
		},
		
		setBodyHeight: function() {
			body = $('body.content-page');

			body.height('auto');
			
			if ($('#page_canvas').height() < body.height())
			{
				body.height('100%');
			}
			else if ($('#page_canvas').height() != body.height())
			{
				body.height('auto');
			}
		},
		
		/* Actions that get run to setup the main navigation actions */
		setupNav: function() {
			// Main navigation items hover event
			$('#pri_navigation ul#nav_left li a').hoverIntent(function() {
				$($(this).parent()).addClass('open'); // remove down arrow by giving it open class
				$.axis41.settings.switching_subnav = $(this).attr("href").replace(/#/, '');
				clearTimeout($.axis41.settings.subnav_timer);
				clearTimeout($.axis41.settings.nav_timer);
				$.axis41.settings.nav_timer = setTimeout('$.axis41.navActions()', 200);
				$.axis41.settings.client_portfolio_timer = setTimeout('$.axis41.clientPortfolioMouseLeave()', 100);
			}, function() {
				
			});
			
			$('#navigation_con #sub_navigation_con #sub_navigation ul li').mouseenter(function() {
				var target = $(this);
				clearTimeout($.axis41.subNavigationShowTimer);
				
				$.axis41.subNavigationShowTimer = setTimeout(function() {
				
					if ($("ul li", $(target)).length > 0) {
						clearTimeout($.axis41.subSubNavigationShowTimer);
						$('#navigation_con #sub_navigation_con #sub_navigation ul li ul').not($('ul', target)).css({
							'display': 'none'
						});
					
						$($(target).parent()).css({
							"border-right": '1px solid #dbe0e2'
						});
					
						var heightToAnimateTo = ((Math.ceil($('ul li', $(target)).length/3)*18)+15);
					
						if (heightToAnimateTo < 64) {
							heightToAnimateTo = 64;
						}
					
						if ($('#sub_navigation').height() < heightToAnimateTo || $('#sub_navigation').height() > 64) {
							$('#sub_navigation_con').animate({ height: heightToAnimateTo+11 }, 400); // shadow
							$('#sub_navigation').animate({ height: heightToAnimateTo }, 400); // blue color
							
							if (heightToAnimateTo != 64) {
								var animationTime = 250;
							}
						}
					
						$.axis41.subSubNavigationShowTimer = setTimeout(function() {
							$('ul', $(target)).css({ height: heightToAnimateTo });
						
							$(target).find('ul').fadeIn(200);
						}, 200+animationTime);
					}
				}, 300);
			});
			
			// Subnavigation mouseleave event
			$('#navigation_con').mouseleave(function(e) {
				if (e.pageY > $(this).height()) {
					if ($(this).css('top').replace(/px/, '') == 0) {
						clearTimeout($.axis41.settings.subnav_timer);
						$.axis41.settings.subnav_timer = setTimeout('$.axis41.subnavMouseLeave()', 800);
					}
				}
			});
			
			// Subnavigation mouseenter event to reset the close timeout
			$('#navigation_con').mouseenter(function() {
				clearTimeout($.axis41.settings.subnav_timer);
			});
		},
		
		subSubMenuCleanUp: function() {
			$('#navigation_con #sub_navigation_con #sub_navigation ul li:has(ul)').each(function() {
				$($(this).parent()).css({
					'border-right': '0'
				});
				
				$('a:first', this).removeClass('hover');
				
				$('ul', $(this)).css({
					'display': 'none'
				});
			});
		},
		
		subSubMenuFadeIn: function(target) {
			$(target).css('display', 'block');
			$('li', target).css('display', 'none').each(function(i) {
				$(this).fadeIn('fast');
			});
		},
		
		/* The actual subnavigation mouseleave action code for hiding the subnavigation when the cursor is out of the subnavigation's bounds */
		subnavMouseLeave: function() {
			clearTimeout($.axis41.subNavigationShowTimer);
			
			$('#sub_navigation_con').animate({
				'top':'-76px',
				'height': '75px'
			}, 400, null, function() {
				$('#sub_navigation ul[id*='+$.axis41.settings.current_active_subnav+']').css({
					'display':'none'
				});
				$.axis41.subSubMenuCleanUp();

				$.axis41.settings.current_active_subnav = null;
			});
			
			$('#sub_navigation').animate({ height: 64 });
			
			$('#pri_navigation ul#nav_left li').removeClass('open'); // remove all open class on nav items
		},
		
		/* closes the client portfolio box */
		clientPortfolioMouseLeave: function() {
			$('#sub_navigation_con').animate({ height: 75 }); // shadow
			$('#sub_navigation').animate({ height: 64 }); // blue color
		},
		
		/* The actual main navigation action code that controls showing/hiding the subnav items */
		navActions: function() {
			var this_subnav = $.axis41.settings.switching_subnav;
			$.axis41.settings.switching_subnav = null;
			
			$($('#pri_navigation ul#nav_left li a[href*='+$.axis41.settings.current_active_subnav+']').parent()).removeClass('open'); // remove open class on the nav item that was open
			
			if ($.axis41.settings.current_active_subnav == this_subnav || $.axis41.settings.current_active_subnav == null) {
				$.axis41.settings.current_active_subnav = this_subnav;
				if (parseFloat($('#sub_navigation_con').css('top').replace(/px/, '')) < 0) {

					$('#sub_navigation ul[id*='+$.axis41.settings.current_active_subnav+']').css({
						'display':'block'
					});

					$('#sub_navigation_con').animate({
						'top':'0'
					}, 400, null, function() {
						
					});
				}
			} else {
				$('#sub_navigation ul[id*='+$.axis41.settings.current_active_subnav+']').each(function() {
					$(this).fadeOut(300);
					$(this).animate({
						'top':'-70px',
						'display':'none'
					}, {
						duration: 400,
						queue: false,
						complete: function(){
							$(this).css({
								'top':'7px'
							});
							
							$.axis41.subSubMenuCleanUp();
						}
					});
				});

				$('#sub_navigation ul[id*='+this_subnav+']').each(function() {
					$(this).fadeIn(300);
					$(this).css({
						'top':"-70px",
						'display':'block'
					}).animate({
						'top':'7px'
					}, {
						duration: 400,
						queue: false
					});
				});

				$.axis41.settings.current_active_subnav = this_subnav;
			}
			return false;
		},
		
		/* Function to setup portfolio images to be the same size as the window and keep aspect ratio */
		setupPortfolioImage: function(path, use_original) {
			if (path == null) {
				return path;
			}
			
			if (use_original == null) {
				use_original = false;
			}
			
			var loaded_file = path;
			loaded_file = loaded_file.split('/');					
			loaded_file = loaded_file[loaded_file.length-1];
			loaded_file = loaded_file.split('.');
			
			var loaded_file_extension = loaded_file[loaded_file.length-1];
			var loaded_file_name = loaded_file.join('.').replace(new RegExp('.' + loaded_file_extension + '$'), '');
			var loaded_file_name_parsed = loaded_file_name;
			
			var loaded_file_name_size = loaded_file_name_parsed.split('_');
			loaded_file_name_size = loaded_file_name_size[loaded_file_name_size.length-1];
			
			if (loaded_file_name_size.match(/^[0-9]{1,}x[0-9]{1,}$/i)) {
				loaded_file_name_parsed = loaded_file_name_parsed.replace(new RegExp("_"+loaded_file_name_size+"$"), '');
			}
			
			/* Check for the right size */
			var size_to_load = "";
			if (use_original == false) {
				for(var i = 0; i < $.axis41.imageSizes.length; i++) {
					if ($.axis41.imageSizes[i][0] >= $(window).width() && $.axis41.imageSizes[i][1] >= $(window).height()) {
						size_to_load = "_"+$.axis41.imageSizes[i][0]+"x"+$.axis41.imageSizes[i][1];
						break;
					}
				}
			}
			
			return path.replace(new RegExp(loaded_file_name+'.' + loaded_file_extension + '$'), '')+loaded_file_name_parsed+size_to_load+"."+loaded_file_extension;			
		},
		
		/* Function to center portfolio images if keeping the aspect ratio means that the image will have to be larger than the window width/height */
		centerPortfolioImage: function(target, proposed_width, proposed_height, website) {
			if (website == null) {
				website = false;
			}

			target = $(target);
			var the_window = $(window);
			
			if (proposed_width > the_window.width() ||  proposed_height > the_window.height()) {
				// images are wide screen so set them to the height of the window
				target.css('height', the_window.height());
			
				// if the window width is wider than the resized image we need to set the image width to the window width
				if (target.width() < the_window.width()) {
					target.css({
						'width'		: the_window.width(),
						'height'	: 'auto'
					});
				}
			}
			
			var margin_top = (the_window.height()/2) - (target.height() / 2);
			var margin_left = Math.floor(the_window.width()/2 - (target.width() / 2));
			
			if (website) {
				margin_top = margin_top - 30;
			}
			
			$(target).css({
				'margin-top' : margin_top + 'px',
				'margin-left' : margin_left + 'px'
			});
		},
		
		portfolioNavigationUp: function () {
			$('#portfolio_nav_con').animate({height: '125px'});
			$('#portfolio_navigation').animate({height: '125px'}).removeClass('closed');
		},
		
		portfolioNavigationDown: function () {
			$('#portfolio_nav_con').animate({height: '59px'});
			$('#portfolio_navigation').animate({height: '59px'}).addClass('closed');
		},
		
		/* function to setup the collapsed/uncollapsed state of the navigation in the portfolio */
		setupPortfolioNavigation: function() {
			// slider box at the bottom
			$('#portfolio_nav_con').hoverIntent(function() {
				if ($.axis41.settings.slideshow.enabled == false) {
					$.axis41.portfolioNavigationUp();
				}
			},
			function() {
				if ($.axis41.settings.slideshow.enabled == false) {
					$.axis41.portfolioNavigationDown();
				}
			});
			
			$.axis41.settings.scroll_api = $('#thumbnail_con').scrollable({
				size: 	10,
				items: 'ul',
				prevPage: '.prev-page',
				nextPage: '.next-page',
				api: true,
				clickable: true,
				onSeek: function() {
					if (this.getPageIndex() > 0) {
						$('#thumb_group_prev').show();
					} else {
						$('#thumb_group_prev').hide();
					}
					
					if (this.getPageIndex() + 1 < this.getPageAmount()) {
						$('#thumb_group_next').show();
					} else {
						$('#thumb_group_next').hide();
					}
				}
			});
			
			$('#thumb_group_prev').click(function() {
				$.axis41.settings.scroll_api.prevPage();
				return false;
			});
			
			$('#thumb_group_next').click(function() {
				$.axis41.settings.scroll_api.nextPage();
				return false;
			});
			
			// ajax to change portfolio images. Next/prev links and thumbnails
			$('#thumbnail_con ul a, #portfolio-prev, #prev, #portfolio-next, #next').bind('click.action', function() {
				$.axis41.portfolioClick(this);
				return false;
			});
		},
		
		portfolioClick: function(obj) {
			// get the image and set the URL
			var the_url = $(obj).attr('href').split('/');
			id = the_url.pop();
			
			var num = parseInt(id);
			
			if (num != id) {
				if (id == "last") {
					id = "#"+id;
				} else {
					id = "/"+id;
				}
				window.location = the_url.join('/')+ id;
			} else {	
				//$.axis41.portfolioNavigationDown();
				$('#portfolio-next span, #portfolio-prev span').removeClass('popout');
				clearTimeout($.axis41.settings.first_item_timer);
				clearTimeout($.axis41.settings.last_item_timer);
				
				$.historyLoad('i' + num, the_url.join('/'));
			}
		},
		
		/* shows prev/next button on porfoliopages */
		portfolioNavigationShowButton: function() {
			$('a', this).fadeIn();
			clearTimeout($.axis41.portfolio_timer);	
		},
				
		/* sets up the scrollable portfolio thumbnails */
		setupPortfolioThumbnails: function() {
			$('.client-row').each(function() {
				var cur = $(this);
				
				var api = cur.scrollable({
					size: 	10,
					items: 'ul',
					prevPage: '.prev-page',
					nextPage: '.next-page',
					api: true
				});
				
				if ($('li', cur).length > 10)
				{
					cur.append('<span class="nav-bttns"><a href="#" class="prev-page">Prev</a><a href="#" class="next-page">Next</a></span>');
					
					var parent = this;
					
					api.onSeek(function() {
						if (api.getPageIndex() > 0) {
							$('.prev-page', parent).show();
						} else {
							$('.prev-page', parent).hide();
						}
						
						if (api.getPageIndex() + 1 < api.getPageAmount()) {
							$('.next-page', parent).show();
						} else {
							$('.next-page', parent).hide();
						}
					});
					
					$('.prev-page', this).click(function() {
						api.prevPage();						
						return false;
					});
					
					$('.next-page', this).click(function() {							
						api.nextPage();					
						return false;
					});
					
					// var nav_bttns = $('.nav-bttns a', this);
					// 					cur.hoverIntent(function() {
					// 						//clearTimeout($.axis41.portfolioThumnails_timer);
					// 						nav_bttns.fadeIn().addClass('over');
					// 					},
					// 					function() {
					// 						nav_bttns.removeClass('over');
					// 						//$.axis41.portfolioThumnails_timer = setTimeout("$('.nav-bttns a:not(.over)').fadeOut();", 500);
					// 					});
				}
			});
		},
		
		/* loads the portfolio page */
		loadPage: function(hash, the_url) {
			if (the_url == null) {
				if (hash) {
					var id = hash.replace(/^i([0-9]+)/, '$1');
					// need to build the url for the image
					var cur = window.location.pathname;
					cur = cur.replace(window.location.hash, '')
					cur = cur.split('/');
					var last = cur.pop();
					cur = cur.join('/');
					
					if (last != parseInt(last)) {
						cur += '/' + last;
					}
					
					//the_url = cur + '/' + id;
					the_url = cur;
				} else {
					the_url = window.location.pathname;
					cur = the_url;
				}
			} else if (hash != null) {
				var id = hash.replace(/^i([0-9]+)/, '$1');
			}
			
			if (id == 'think' || id == 'speak') {
				return;
			}
			
			$.axis41.addLoadingBox();
			//var image = {};
			if ($.axis41.dataForCurrentSet.url != the_url) {
				$.axis41.dataForCurrentSet.url = the_url;
				
				if (the_url.indexOf("?", 0) === -1) {
					var ajax_url = the_url+'?ajax';
				} else {
					var ajax_url = the_url+'&ajax';
				}
				
				$.getJSON(ajax_url, function(image) {
					$.axis41.dataForCurrentSet.data = image;
					$.axis41.cachedImages = [];
					if (id == null) {
						image = image[0];
					} else {
						if (id == "last") {
							image = $.axis41.dataForCurrentSet.data[$.axis41.dataForCurrentSet.data.length-1];
						} else {
							image = $.axis41.findCurrentDataById(id);
						}
					}
					image.loaded = true;
					$.axis41.current_image_data = image;
					
					$.axis41.changePortfolioImage(image.path, image.logo, image.website);
					$.axis41.updatePortfolioTitles(image);
					$.axis41.updatePrevNextLinks(the_url+"/"+image.id);
					$.axis41.cacheCurrentImageSet(true);
				});
			} else {
				if (id == "last") {
					var image = $.axis41.dataForCurrentSet.data[$.axis41.dataForCurrentSet.data.length-1];
				} else {
					var image = $.axis41.findCurrentDataById(id);
				}
				image.loaded = true;
				$.axis41.current_image_data = image;
				
				$.axis41.changePortfolioImage(image.path, image.logo, image.website);
				$.axis41.updatePortfolioTitles(image);
				$.axis41.updatePrevNextLinks(the_url+"/"+image.id);
				$.axis41.cacheCurrentImageSet();
			}
		},
		
		findCurrentDataById: function(id, returnPosition) {
			if (returnPosition == null) {
				returnPosition = false;
			}
			
			for(var i = 0; i < $.axis41.dataForCurrentSet.data.length; i++) {
				if ($.axis41.dataForCurrentSet.data[i].id == id) {
					if (returnPosition == false) {
						return $.axis41.dataForCurrentSet.data[i];
					} else {
						return i;
					}
				}
			}
			
			return {};
		},
		
		updatePortfolioTitles: function(image) {
			if (image.client != null && image.client != '') {
				$('#portfolio-title').html(image.client.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
			}
			
			// change title
			$('#project_name').html(image.name.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
		},
		
		updatePrevNextLinks: function(the_url) {
			// change which thumbnail is selected
			$('#thumbnail_con .selected').removeClass('selected');
			
			// find which thumbnail is the current one and highlight it
			the_url = the_url.replace(window.location.protocol + '//' + window.location.hostname, '');
			var thumb_lis = $('#thumbnail_con li');
			var prev_url = next_url = current_number = 0;
			for(i = 0; i < thumb_lis.length; i++) { // looping through each thumbnail on every ajax call probably isn't the best
				var link = $('a', thumb_lis[i]);

				if (the_url == link.attr('href')) {
					$(thumb_lis[i]).addClass('selected');
					$('#prev').text(i + 1);
					
					current_number = i;
					break;
				}
			}
			
			// set the prev/next urls
			var prev_number = current_number - 1;
			if (prev_number < 0) {
				prev_number = 0;
			}
			
			var next_number = current_number + 1;
			if (next_number >= thumb_lis.length) {
				next_number = thumb_lis.length - 1;
			}
			
			prev_url = $('a', thumb_lis[prev_number]).attr('href');
			next_url = $('a', thumb_lis[next_number]).attr('href');
			if (prev_number != current_number) {
				$('#portfolio-prev span').removeClass('show').removeClass('popout');
				$('#portfolio-prev, #prev').attr('href', prev_url);
			} else {
				$('#portfolio-prev span').addClass('show');
				$('#portfolio-prev').attr('href', $('#portfolio-prev span').attr('link'));
				
				if ($.axis41.settings.slideshow.enabled == false) {
					//$.axis41.settings.first_item_timer = setTimeout(function() {
						$('#portfolio-prev span').addClass('popout');
					//}, $.axis41.settings.slideshow.delay*1000);
				}
			}
			
			if (next_number != current_number) {
				$('#portfolio-next span').removeClass('show').removeClass('popout');
				$('#portfolio-next, #next').attr('href', next_url);
			} else {
				$('#portfolio-next span').addClass('show');
				$('#portfolio-next').attr('href', $('#portfolio-next span').attr('link'));
				if ($.axis41.settings.slideshow.enabled == false) {
					//$.axis41.settings.last_item_timer = setTimeout(function() {
						//$.axis41.portfolioNavigationUp();
						$('#portfolio-next span').addClass('popout');
					//}, $.axis41.settings.slideshow.delay*1000);
				}
			}
			
			$('#portfolio-next span, #portfolio-prev span').unbind('.autopop').bind('mouseout.autopop', function() {
				$(this).removeClass('popout');
			});
			
			$.axis41.settings.current_portfolio_number = current_number;
			if ($.axis41.settings.initialPageLoad == true) {
				$.axis41.scrollPortfolioThumbnails();
				$.axis41.settings.initialPageLoad = false;
			}
		},
		
		/* change image */
		changePortfolioImage: function(path, logo, website, useOriginalPath) {
			// append new image to the page
			$('#page_canvas .hide').remove();
			$('#page_canvas').append('<img class="hide" />');
			
			var img = $('#page_canvas .hide');
			if (useOriginalPath != true) {
				var logo_website = (logo == true || website == true) ? true : false;
				
				var imgPath = $.axis41.setupPortfolioImage(path, logo_website);
			} else {
				var imgPath = path;
			}
			
			img.load(function() {
				$.axis41.removeLoadingBox();
				
				$.axis41.centerPortfolioImage(this, $(this).width(), $(this).height(), website);
				
				// fade out whole canvas
				$('#page_canvas').fadeOut(200, function() {
					$('#current-image').remove(); // remove it after fading it out
				
					// add or remove room background
					if (logo) {
						$('#page_canvas').addClass('logo');
					} else {
						$('#page_canvas').removeClass('logo');
					}
					
					if (website) {
						$('#page_canvas').addClass('website');
					} else {
						$('#page_canvas').removeClass('website');
					}
					
					$('#page_canvas .hide').show().removeClass('hide').addClass('fullscreen').attr('id', 'current-image');
					
					$('#page_canvas').fadeIn(function() {
						if ($.axis41.settings.slideshow.enabled == true) {
							$.axis41.runSlideshow();
						}
					}); // fade everything back in
				});
			}).error(function(e) {
				$.axis41.changePortfolioImage(path, logo, website, true);
			}).attr('src', imgPath);
		},
		
		cacheCurrentImageSet: function(stopTimers) {
			if ($.axis41.dataForCurrentSet.data != null) {
				if (stopTimers == true) {
					for(var t = 0; t < $.axis41.cacheImageTimmers.length; t++) {
						clearTimeout($.axis41.cacheImageTimmers[t]);
					}
					$.axis41.cacheImageTimmers = [];
				}
				
				var currentImagePos = $.axis41.findCurrentDataById($.axis41.current_image_data.id, true);
				var timerInterator = 0;
				var nextCacheCountStop = $.axis41.dataForCurrentSet.data.length;
				var additionalLength = 400;
				
				for(var i = currentImagePos; i < nextCacheCountStop; i++) {
					if ($.axis41.dataForCurrentSet.data[i].cached == null && $.axis41.cacheImageTimmers[i] == null) {
						clearTimeout($.axis41.cacheImageTimmers[i]);
						
						if (parseInt(i-currentImagePos) < 14) {
							var timerLength = 250;
						} else {
							var timerLength = 2250;
						}
						
						$.axis41.cacheImageTimmers[i] = setTimeout("$.axis41.cacheImage(" + i + ")", timerLength*(timerInterator+1));
						timerInterator++;
					}
				}
				
				timerInterator = 0;
				var prevCacheCountStop = 0;
				
				for(var i = currentImagePos; i >= prevCacheCountStop; i--) {
					if ($.axis41.dataForCurrentSet.data[i].cached == null && $.axis41.cacheImageTimmers[i] == null) {
						clearTimeout($.axis41.cacheImageTimmers[i]);
						
						if (parseInt(currentImagePos-i) > 14) {
							var timerLength = 375;
						} else {
							var timerLength = 2375;
						}
											
						$.axis41.cacheImageTimmers[i] = setTimeout("$.axis41.cacheImage(" + i + ")", timerLength*(timerInterator+1));
						timerInterator++;
					}
				}
			}
		},
		
		cacheImage: function(pos) {
			var image = $.axis41.dataForCurrentSet.data[pos];
			if (image.cached == null) {
				$.axis41.cachedImages[pos] = new Image();
				
				var logo_website = (image.logo == true || image.website == true) ? true : false;
				$.axis41.cachedImages[pos].src = $.axis41.setupPortfolioImage(image.path, logo_website);
				//console.log('cached: '+$.axis41.cachedImages[pos].src);
				$.axis41.dataForCurrentSet.data[pos].cached = true;
			}
		},
		
		/* sets up the show/hide of the client list */
		setupClientList: function() {
			$('#client-list-trigger').click(function() {
				var cur = $(this);
				if (cur.hasClass('closed')) {
					$('.client-list').slideDown();
					cur.removeClass('closed').addClass('open');
				} else {
					$('.client-list').slideUp();
					cur.removeClass('open').addClass('closed');
				}
				
				return false;
			});
		},
		
		/* sets up collapse boxes */
		setUpCollapseBoxes: function() {
			$('.collapse-box h3 a').click(function() {
				var cur = $(this);
								
				if (cur.hasClass('open')) {
					cur.removeClass('open').addClass('close');
					$('div', cur.parent().parent()).slideUp();
				} else {
					$('a.open').removeClass('open').addClass('close');
					$('.collapse-box div').slideUp();
					
					cur.removeClass('close').addClass('open');
					$('div', cur.parent().parent()).slideDown();
				}
				
				return false;
			});
		},
		
		/* shows the loading box by appending the HTML to the page */
		addLoadingBox: function() {
			$.axis41.removeLoadingBox();
			if ($('#loading-container').length < 1) {
				$('body').append('<div id="loading-container" style="display: none;"><div id="loading"><img src="' + site_base_url + '/public/images/loader_blue.gif" /><div></div>');
			}
			
			$.axis41.loadingBoxTimer = setTimeout('$.axis41.showLoadingBox()', 250);
		},
		
		showLoadingBox: function() {
			$('#loading-container').show();
		},
		
		/* hides the loading box by removing it from the page */
		removeLoadingBox: function() {
			clearTimeout($.axis41.loadingBoxTimer);
			$('#loading-container').hide();
		},
		
		/* sets up the map popup window */
		setupMapPopup: function() {
			$('.map a, .view-map').click(function() {
				$('.map-popup').show('fast');
				return false;
			});
			
			$('.map-popup').click(function() {
				$(this).hide('fast');
				return false;
			});
		},
		
		processKeyCommands: function(e) {
			//e.keyCode
			if (e.keyCode == 39 || e.keyCode == 33) {
				$('#portfolio-next:visible').trigger("click");
				return;
			}
			
			if (e.keyCode == 37 || e.keyCode == 34) {
				$('#portfolio-prev:visible').trigger("click");
				return;
			}
			
			
			if (e.keyCode == 13) {
				if ($.axis41.modifierText == "41") {
					$.axis41.modifierText = null;
					window.location.replace("http://www.youtube.com/watch?v=FJ3oHpup-pk");
				}
				if ($.axis41.modifierText == "home") {
					$.axis41.modifierText = null;
					window.location.replace(site_base_url+"/");
				}
				
				if ($.axis41.modifierText == null || $.axis41.modifierText != "") {
					$.axis41.modifierText = "";
				}
			}
			
			if (e.which > 0) {
				if ($.axis41.modifierText == null) {
					$.axis41.modifierText = "";
				}
				
				$.axis41.modifierText = $.axis41.modifierText+String.fromCharCode(e.which);
			}
		}
	});/* END OF CLASS */
	
	
	/**
	*	Event Handlers
	*/
	/* Run when the document has loaded */
	$(document).ready(function() {
		/* Check to make sure that an instance of the plugin is running */
		if ($.axis41 == undefined) {
			$.axis41 = new Axis41();
		}
		
		$.axis41.init();
	});
	
	$(document).keydown(function(e) {
		clearTimeout($.axis41.processKeyCommandsTimer);
		$.axis41.processKeyCommandsTimer = setTimeout(function() {
			$.axis41.processKeyCommands(e);
		}, 200);
	});
})(jQuery);
