$(document).ready(function() {

	//====================================================================
	// Setup of page items and 'global' vars
	//====================================================================
	var dragdeal, currentNavElement, currentLocation, navTimeout, newWidth, newHeight, homepageInterval, pane, api, handheld;
	var mobNavDisplayRanOnce = false;
	var currentItem = 0;
	var introCompleted = false;
	var secondBack = false;
	var singleImageLoad = false;
	var locationArray = ['/home', '/non-commissioned', '/commissioned', '/film', '/news', '/about', '/contact'];
	var dontRunAgainCheck = false;

	if ($(window).width() <= 480) {
		handheld = true;
		$('<div id="top_red_bar"></div>').prependTo('#nav_container');
	}

	eventHandlers();

	pageSetup();

	bindNextPrevToImages();

	$.address.tracker();



	function eventHandlers() {
		////////console.log('eventHandlers');
		$("#butt_input").live({
			mouseenter: function() {
				$(this).attr('style', 'color: #000000;');
			},
			mouseleave: function() {
				$(this).attr('style', 'color:#949494;');
			}
		});

		$(document).bind("orientationChanged", function() {
			handleScale($(window).width(), $(window).height());
			if (newHeight < 760) {
				$('#footer').hide();
			}
		});

		$(window).resize(function() {
			if (this.resizeTO) clearTimeout(this.resizeTO);
			this.resizeTO = setTimeout(function() {
				$(this).trigger('resizeEnd');
			},
			30);
		});

		$(window).bind('resizeEnd', function() {
			newWidth = $(this).width();
			newHeight = $(this).height();
			handleScale(newWidth, newHeight, true);

			pageSizing();

			if (newHeight < 760) {
				$('#footer').hide();
			}

		});

		$('a#back_to_top').live('click', function() {
			$('html, body').animate({
				scrollTop: 0
			},
			300);
			return false;
		});

		$(document).keyup(function(event) {
			event.preventDefault();
			switch (event.keyCode) {
			case 37:
				paginationPrev();
				break;
			case 38:
				paginationUp();
				break;
			case 39:
				paginationNext();
				break;
			case 40:
				paginationDown();
				break;
			case 27:
				$('#background_overlay').fadeOut(300, function() {
					$('#background_overlay').attr('style', 'top: -99999px');
					$('#background_overlay').empty();
				});
				break;
			}

			navigationShowHide();
			return false;
		});

		if (!handheld) {
			$("#main_content").touchwipe({
				wipeLeft: function() {
					if (currentLocation !== '/index.php') {
						paginationNext();
					}
				},
				wipeRight: function() {
					if (currentLocation !== '/index.php') {
						paginationPrev();
					}
				},
				min_move_x: 20,
				min_move_y: 20,
				preventDefaultEvents: true
			});
		}

		$.address.change(function(event) {
			if ((event.value == "/")) {
				if (handheld) {
					introCompleted = true;
					getAjaxDataForLinkLocation(event.value);

				} else {
					introCompleted = false;
					getAjaxDataForLinkLocation(event.value);
				}
			} else {

				if (handheld) {

					if ((event.value == '/commissioned') || (event.value == '/non-commissioned')) {

						var passLocation = event.value;
						passLocation = passLocation.replace(/\//, '');
						getAjaxDataForLinkLocation(event.value);

					} else {
						////////console.log(event.value);
						$('mobile_sub').remove();
						introCompleted = true;
						currentLocation = event.value;
						$('#nav_container div, #nav_container ul').show();
						//	$('#main_content').empty();
						getAjaxDataForLinkLocation(event.value);
						//$('#nav_container').css('background', 'url(../img/redbar.png) top left repeat-x');	
					}

				} else {

					introCompleted = true;
					currentLocation = event.value;
					$('#nav_container div, #nav_container ul').show();
// error here?		$('#main_content').empty();
					$('#main_content').empty();

					getAjaxDataForLinkLocation(event.value);				
					$('#nav_container').css('background', 'url(../img/redbar.png) top left repeat-x');

				}

				dontRunAgainCheck = true;
			}

			return false;
		});

		//	ehre we go go gog ogogogogogogogoogogooog
		if (handheld) {
			$('#top_level_nav li a').live('click', function() {
				//console.log('1. #top_level_nav li a clicked');
				var itemClicked = $(this).text();

				$('#top_red_bar').empty();
				$('<span>' + itemClicked + '</span>').appendTo('#top_red_bar');

				$('#nav_container li').hide();
				$('#top_red_bar').attr('style', 'height: 12px');

				return false;
			});
		}

		if (handheld) {
			$('#top_red_bar').live('click', function() {
				var itemClicked = $(this).text();
				//console.log('red bar has been clicked');
				//highlight correct item, look up html contents of each li and compare to itemClicked add class selected to a tag					
				$('#nav_container li a').each(function() {

					if (itemClicked == $(this).text()) {
						$(this).removeClass().addClass('selected');
					} else {
						$(this).removeClass();
					}

				});

				/*				if (secondBack) {

					$(this).attr('style', 'height: 2px; padding-top: 6px;');
					$('#nav_container li').fadeIn(300);

					$('#mobile_sub, .sub_nav').remove();

					$(this).empty();

				} else {
*/
				$('#mobile_sub, .sub_nav').remove();

				$('#top_red_bar span').hide();
				$('#top_red_bar').attr('style', 'height: 0px; padding-top: 8px;');
				$('#nav_container li').show();

				$('#top_level_nav li#home_link').hide();

				//				}
				return false;
			});

		}



		$('#nav_container .sub_nav li a').live('click', function() {
			//console.log('2. #nav_container .sub_nav li a clicked');
			introCompleted = true;

			secondBack = false;

			var cleanedLocation = currentLocation.split(/\?/);

			currentLocationXXX = currentLocation.split(/\?/);

			cleanedLocation = cleanedLocation[1].replace(' ', '+');

			var addressURL = $.address.queryString();

			if ((addressURL != cleanedLocation) && (dontRunAgainCheck == true)) {

				introCompleted = true;

				$('#main_content').fadeOut(30).empty();

//				$('#main_content').hide().empty();

				renderSectionLanding(currentLocationXXX[0], addressURL);

			}

			currentLocation = unescape($(this).attr('href'));

			currentItem = 0;

			navigationShowHide();

			return false;

		});

		$('.vimeo, #gallery_news img').live('click', function() {
			paginationNext();
			return false;
		});

		$('a.news_link_clickable').live('click', function() {

			if (!handheld) {

				window.location.href($(this).attr('href'));

				return false;

			} else {

				//				window.location.href($(this).attr('href'));
				mobile_updateNavigation('Film', true);

				//				return false;
			}

		});

		$('#gallery_film ul li .play_link').live('click', function() {
			var vimeoLink = $(this).parent().find('.vimeo').attr('href');

			var videoPosW = (newWidth / 2) - 375;
			var videoPosH = (newHeight / 2) - 250;

			if (handheld) {
				window.open(vimeoLink + '?autoplay=1', '_self', false);
			} else {
				var vimeoContainer = '<div class="vimeo_container"><iframe style="position: absolute; margin-top: ' + videoPosH + 'px; margin-left: ' + videoPosW + 'px;" src="' + vimeoLink + '?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="744" height="500" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe><div id="close_vimeo" style="display:block; position: absolute; top: ' + (videoPosH + 508) + 'px; left: ' + videoPosW + 'px; width: 744px;  text-align: right; color: #FFFFFF; cursor: pointer;">Back to films</div></div>';

				$('#background_overlay').empty();

				$(vimeoContainer).appendTo('#background_overlay');
				$('#background_overlay').attr('style', 'top: 0;').fadeIn(600);
			}

			return false;

		});

		$('#close_vimeo').live('click', function() {
			$('#background_overlay').fadeOut(300, function() {
				$('#background_overlay').attr('style', 'top: -99999px');
				$('#background_overlay').empty();
			});
			return false;
		});

		$('#prev_img').live('click', function() {
			paginationPrev();
			navigationShowHide();
		});

		$('#next_img').live('click', function() {
			paginationNext();
			navigationShowHide();
		});

		if (!handheld) {
			$('#nav_container').mouseenter(function() {

				if (navTimeout) {

					$('#nav_container').animate({
						width: '140px'
					},
					300, function() {
						//						$('#top_level_nav, #subnavs_container, #info_container, #footer').fadeIn(300);
						$('#top_level_nav, #subnavs_container, #info_container').fadeIn(300);
						navigationShowHide();
					});
				}
				return false;
			});

			$('div#nav_container').live('click', function() {

				$('#nav_container').animate({
					width: '140px'
				},
				300, function() {
					//					$('#top_level_nav, #subnavs_container, #info_container, #footer').fadeIn(300);
					$('#top_level_nav, #subnavs_container, #info_container').fadeIn(300);
					navigationShowHide();
				});

				return false;
			});

		}

		return false;
	}



	function bindNextPrevToImages(thisItem) {
		////////console.log('bindNextPrevToImages()');
		$('.gallery ul li .image_container img').not('#gallery_home').unbind().bind('click', function() {
			paginationNext();
		});

		if ($('.gallery ul li').eq(thisItem).attr('class') == 'onlychild') {
			$('.gallery ul li .image_container img').not('#gallery_home').eq(thisItem).unbind().bind('click', function() {
				singleImageLoad = true;
				paginationNext();

			});
		}
		return false;
	}



	function runIntro() {
		////////console.log('runIntro');
		if (introCompleted == false) {

			$('#main_content, #nav_container div, #nav_container ul').hide();

			if (!handheld) {
				$('<img id="red_animate" style="position:absolute; top:0; left:0;" src="img/redbar.png" width="10" height="2" alt="" />').prependTo('#nav_container');
				$('#red_animate').delay(450).animate({
					'width': 140
				},
				1000);
			}

			$('h1').delay(450).fadeIn(450).delay(1000).fadeOut(450, function() {

				if (handheld) {
					$('#main_content, #nav_container ul, #nav_container div').show();

					currentLocation = '/index.php';

					$('#top_red_bar').attr('style', 'height: 0px');

				} else {

					$('#nav_container').css('background', 'url(../img/redbar.png) top left repeat-x');

					$('#main_content, #nav_container div, #nav_container ul').delay(900).fadeIn(450, function() {

						if (introCompleted == false) {
							currentLocation = '/index.php';
							controlNavHighlighting(currentLocation);
							renderDynamicPage('/index.php');
							clearTimeout(navTimeout);
							navigationShowHide();
						}

						$('#red_animate').remove();

						introCompleted = true;

					});
				}
			});
		}

		return false;
	}



	function pageSetup() {
		////////console.log('pageSetup');
		window.setTimeout(hideUrlBar, 0);

		newWidth = $(window).width();
		newHeight = $(window).height();

		if (!handheld) {
			//			$('#nav_container').attr('style', 'height:' + ($(window).height() - 100) + 'px');
			$('.gallery_contain, #footer').attr('style', 'width: ' + (($(window).width() - 200) + 'px;'));
			$('<div id="background_overlay"></div>').prependTo('body').hide();
		}

		$('ul li .image_container, ul li .image_info').hide();

		$('#nav_container ul li a, #nav_container .subnav ul li a').address();

		$('<div id="info_container"></div>').appendTo('#nav_container');

		$('h2.nav_title').hide();

		$('#main_content, #nav_container div, #nav_container ul').hide();

		return false;
	}



	function pageSizing(disableFooter) {

		if (!handheld) {
			$('.gallery_contain, #footer').attr('style', 'width: ' + (newWidth - 210) + 'px;');
			if (disableFooter) {
				$('#footer').hide();
			}
		}
		return false;
	}



	function handleScale(newWidth, newHeight, resize) {

		if (handheld) {
			$('body').height(($(window).height() + 40));
		}

		$('.gallery ul li .image_container').find('img').each(function() {
			var thisWidth, thisHeight, thisAspect, windowHeight, windowWidth;

			thisAspect = $(this).attr('width') / $(this).attr('height');

			if (!handheld) {
				//dirty ipad check
				if (($(window).height() == 946) && ($(window).width() == 768)) {
					windowHeight = newHeight - 300;
					windowWidth = newWidth - 300;
				} else {
					windowHeight = newHeight - 100;
					windowWidth = newWidth - 300;
				}

			} else {
				windowHeight = newHeight - 16;
				windowWidth = newWidth - 40;
			}

			if (parseInt($(this).attr('height'), 10) >= parseInt($(this).attr('width'), 10)) {

				thisHeight = windowHeight;
				thisWidth = windowHeight * thisAspect;

				$(this).css('width', Math.round(thisWidth));
				$(this).css('height', Math.round(thisHeight));

			} else {

				if ((parseInt($(this).attr('width'), 10) > windowWidth) || (parseInt($(this).attr('height'), 10) > windowHeight)) {

					thisWidth = windowWidth;
					thisHeight = windowWidth / thisAspect;

					if (thisHeight > windowHeight) {

						thisHeight = windowHeight;
						thisWidth = thisHeight * thisAspect;

					}

					$(this).css('width', Math.round(thisWidth));
					$(this).css('height', Math.round(thisHeight));

				}
			}

		});

		if (resize) {
			$('.gallery_contain').scrollTo($(".gallery ul li").eq(currentItem));
		}

		//update video position
		if (!handheld) {
			var videoPosW = (newWidth / 2) - 375;
			var videoPosH = (newHeight / 2) - 250;
			$('iframe').attr('style', 'margin-top: ' + videoPosH + 'px; margin-left: ' + videoPosW + 'px;');
			$('#close_vimeo').attr('style', 'top: ' + (videoPosH + 508) + 'px; left: ' + videoPosW + 'px; width: 744px; text-align: right; color: #FFFFFF; display: block; position: absolute;');
		}

		window.setTimeout(hideUrlBar, 0);

		return false;

	}



	function renderNext() {
		////////console.log('renderNext');
		var _image, item = renderNext.list.shift();

		if (!item) {
			if (handheld) {
				$('#back_to_top').remove();
				$(".flat_gallery").after('<a id="back_to_top" href="" onclick="">Back to top</a>');
			}
			return false;
		}

		if (!handheld) {
			$('<div class="loading_div" style="position: absolute; top: 0; left:0;"><img src="../img/anibar.gif" height="2" width="10" /></div>').prependTo($(item).closest('li'));
		}

		_image = $('<img />').bind("load", function() {

			$('.loading_div').remove();
			$('.play_link').delay(600).fadeIn(300);

			if (handheld) {
				$(item).closest('.image_container').fadeIn(300, function() {
					renderNext();
				});
			} else {
				$(item).closest('.image_container').fadeIn(600, function() {
					renderNext();
				});
			}

		}).attr('src', $(item).attr('src'));

		return true;
	}



	function navigationShowHide() {
		////////console.log('navigationShowHide');
		if (!handheld) {
			clearTimeout(navTimeout);

			navTimeout = setTimeout(function() {

				var timesRun = 0;

				$('#top_level_nav, #subnavs_container, #info_container').fadeOut(300, function() {
					if (timesRun == 0) {

						$('#top_level_nav, #subnavs_container, #info_container, #footer').hide();

						$('#nav_container').animate({
							width: '10px'
						},
						300, function() {
							$('#top_level_nav, #subnavs_container, #info_container, #footer').hide();
						});

						timesRun++;
					}
				});

			},
			80000);
		}

		return false;
	}



	function getAjaxDataForLinkLocation(location_link) {
		////////console.log('getAjaxDataForLinkLocation(' + location_link + ')' + ' : introCompleted = ' + introCompleted);
		var htmlContent = '';

		if ((location_link == '/') || (location_link == '')) {
//error here?
//			$('#main_content, #nav_container div, #nav_container ul').hide();
			$('#nav_container div, #nav_container ul').hide();

			introCompleted = false;
			location_link = '/home';
			runIntro();

			return false;
		}

		switch (location_link) {
		case '/home':

			$.address.title('David Gill - Home');

			if (!handheld) {
				$('.sub_nav').fadeOut(450);

				if (introCompleted == true) {
					renderDynamicPage('/index.php');
				}

				currentLocation = '/index.php';
				controlNavHighlighting(currentLocation);
			} else {
				mobNavDisplayRanOnce = true;
				mobile_getHome();

			}
			break;

		case '/non-commissioned':
			$.address.title('David Gill - Non-commissioned');
			if (!handheld) {
				renderSectionLanding('/non-commissioned.php', 'item=A to E');
				currentLocation = '/non-commissioned?item=A to E';
			} else {
				mobile_getNonCommissioned();
			}
			break;

		case '/commissioned':
			$.address.title('David Gill - Commissioned');
			if (!handheld) {
				renderSectionLanding('/commissioned.php', 'item=Alpen');
				currentLocation = '/commissioned?item=Alpen';
			} else {
				mobile_getCommissioned();
			}
			break;

		case '/film':
			$.address.title('David Gill - Film');

			if (!handheld) {
				renderDynamicPage('/film.php');
				currentLocation = '/film.php';
				controlNavHighlighting(currentLocation);
			} else {
				mobile_getFilm();
			}
			break;

		case '/news':
			$.address.title('David Gill - News');
			if (!handheld) {
				renderDynamicPage('/news.php');
				currentLocation = '/news';
				controlNavHighlighting(currentLocation);
			} else {
				mobile_getNews();
			}
			break;

		case '/about':
			$.address.title('David Gill - About');
			if (!handheld) {
				$('#info_container .image_info, #next_prev_container').fadeOut(300);
				renderStaticPage('/about.php');
				currentLocation = '/about';
				controlNavHighlighting(currentLocation);
			} else {
				mobile_getAbout();
			}
			break;

		case '/contact':
			$.address.title('David Gill - Contact');
			if (!handheld) {
				$('#info_container .image_info, #next_prev_container').fadeOut(300);
				renderStaticPage('/contact.php');
				currentLocation = '/contact';
				controlNavHighlighting(currentLocation);
			} else {
				mobile_getContact();
			}
			break;

		default:

			if (currentLocation.search('non-commissioned') != -1) {

				$.address.title('David Gill - Non-commissioned');

				var location = currentLocation.split(/\?/);
				renderSectionLanding('/non-commissioned.php', location[1]);

			} else {

				if (currentLocation.search(/film/) != -1) {

					$.address.title('David Gill - Film');

					var location = currentLocation.split(/\?\i\=/);

					if (!handheld) {
						renderDynamicPage('/film.php', location[1]);
					} else {
						mobile_getFilm();
					}

				} else {

					$.address.title('David Gill - Commissioned');

					var location = currentLocation.split(/\?/);

					renderSectionLanding('/commissioned.php', location[1]);

				}

			}

			break;
		}

		return false;
	}



	function renderStaticPage(ourUrl) {
		////////console.log('renderStaticPage(' + ourUrl + ')');
		$('h1').hide();
		$.ajax({
			url: ourUrl,
			beforeSend: function() {
				htmlContent = '';

				$('#main_content').fadeOut(30).empty();

				$('<div class="loading_div" style="position: absolute; top: 0; left:0;"><img src="../img/anibar.gif" height="2" width="10" /></div>').appendTo('#main_content');

				$('#subnavs_container, #info_container').empty();

				$('mobile_sub').remove();
			},
			success: function(htmldata) {

				htmlContent = $(htmldata).find('div.section_container');

			},
			complete: function() {

				$('.loading_div').hide();

				$(htmlContent).appendTo('#main_content');

				$('#main_content').show();

				$('div.section_container').hide();

				$('#main_content, #main_content div.section_container').fadeIn(600);

				if (handheld) {
					$('#info_container, #mobile_sub').hide();

				}

				pageSizing();

			}
		});
		return false;
	}



	function rotateHomePageImages(num, imgSrc) {
		////////console.log('rotateHomePageImages(' + num + ', ' + imgSrc + ')');	
		var rotateLength = $('.gallery ul li .image_container img').length;

		if (num == (rotateLength - 1)) {
			num = 0;
		} else {
			num = num + 1;
		}

		var nextSrc = imgSrc[num];

		$('.gallery ul li .image_container img').eq(0).delay(6000).fadeOut(600, function() {
			$('.gallery ul li .image_container img').eq(0).attr('src', nextSrc);
		}).delay(300).fadeIn(600, function() {
			rotateHomePageImages(num, imgSrc);
		});

		return false;
	}



	function renderDynamicPage(ourUrl, location) {

		$('h1').hide();
		////console.log('renderDynamicPage(' + ourUrl + ')');
		$('#nav_container .sub_nav').fadeOut(30).remove();

		$.ajax({
			url: ourUrl,
			beforeSend: function() {
				htmlContent = '';
				$('#main_content').empty().show();
				$('<div class="loading_div" style="position: absolute; top: 0; left:0;"><img src="../img/anibar.gif" height="2" width="10" /></div>').appendTo('#main_content');
				$('#info_container').empty();
			},
			success: function(htmldata) {
				htmlContent = $(htmldata).find('div.section_container');
				$(htmlContent).appendTo('#main_content');
			},
			complete: function() {

				currentItem = 0;

				$('.loading_div').hide();

				var imageInfo = $('.gallery .image_info');

				$(imageInfo[0]).clone().appendTo('#nav_container #info_container');

				if (!handheld) {
					$('#info_container .image_info').fadeIn(300, function() {

						if (currentLocation != '/index.php') {
							generateImagePagination();
						}

					});
				}

				$('.gallery ul li .image_container, .gallery ul li .image_info').hide();

				controlNavHighlighting(currentLocation);
				pageSizing();
				handleScale(newWidth, newHeight);

				if (ourUrl == '/film.php') {
					$('<div class="play_link">Play film</div>').appendTo('.gallery ul li').hide();

				}

				if (handheld) {
					$('#info_container').remove();
				}

				if (ourUrl == '/index.php') {

					if (!handheld) {
						$('.gallery_contain ul li').attr('style', 'height: ' + ($(window).height() + -195) + ';');
					} else {
						$('#info_container').remove();
						$('#footer').empty();
					}

					renderNext.list = $('.gallery ul li .image_container img').eq(0).get();
					renderNext();

					var arrayOfHomepageImageSrc = new Array();

					$('.gallery ul li .image_container img').each(function(i) {
						arrayOfHomepageImageSrc[i] = $(this).attr('src');
					});

					rotateHomePageImages(1, arrayOfHomepageImageSrc);

				} else {

					renderNext.list = $('.gallery ul li .image_container img').slice(0, 2).get();
					renderNext();

				}

				if (location) {
					var timeTest = setTimeout(function() {
						location = location - 1;
						$('.gallery_contain').scrollTo($(".gallery ul li").eq(location));
						currentItem = currentItem + location;
						manageItemDescriptions($(".gallery ul li").eq((currentItem)));
						renderNext.list = $('.gallery ul li .image_container img').eq(location).get();
						renderNext();
						clearTimeout(timeTest);
					},
					300);
				}

			}
		});

		navigationShowHide();

		return false;
	}



	function quietLoadSection(ourUrl, ourQuery) {
		////////console.log('quietLoadSection(' + ourUrl + ', ' + ourQuery + ')');
		var htmlContent;

		$.ajax({
			type: 'POST',
			url: ourUrl,
			data: ourQuery,
			beforeSend: function() {

				htmlContent = '';
				$('.gallery ul li.loading_container').remove();
				$('<li class="loading_container"></li>').appendTo('.gallery ul');
				$('<div class="loading_div_quiet"><img src="../img/anibar.gif" height="2" width="10" /></div>').appendTo('.gallery ul li.loading_container');
				$('.gallery ul li.loading_container').show();
				$('.loading_div').show();

			},
			success: function(htmldata) {

				htmlContent = $(htmldata).find('div.section_container .gallery ul li');

				var checkCurrentLastItem = $('.gallery ul li .image_container img').last().attr('src');

				var checkItemToLoadIn = $(htmlContent).find('.image_container img').eq(0).attr('src');

				if (checkCurrentLastItem == checkItemToLoadIn) {

					singleImageLoad = true;
					getLocation(currentLocation, 1, 'load');

					return false;

				}

				$(htmlContent).find(".image_info, .image_container").attr("style", "display:none");

				$(htmlContent).appendTo('.gallery ul');

				$('.gallery ul li.loading_container').remove();

				handleScale(newWidth, newHeight);

				return false;
			},
			complete: function() {

				if (!singleImageLoad) {
					//	renderNext.list = $('.gallery ul li .image_container img').slice(currentItem, (currentItem + 2)).get();
					//	renderNext();
					singleImageLoad = false;
				}

				bindNextPrevToImages(currentItem);

			}
		});

		return true;
	}



	function getLocation(currentLocation, direction, loadorcheck) {
		////////console.log('getLocation(' + currentLocation + ', ' + direction + ', ' + loadorcheck +')');
		var cleanedLocation = currentLocation;

		if (cleanedLocation.search(/php/) == -1) {
			cleanedLocation = cleanedLocation.replace('?', '.php\?');
		}
		cleanedLocation = cleanedLocation.replace(/\+/g, ' ');

		if ($('.sub_nav li a')) {

			var arrayOfWork = new Array();
			var query, location, splitstring, nextLocation, arrIndex;

			$('ul.sub_nav li a').each(function(i) {
				arrayOfWork[i] = unescape($(this).attr('href'));
			});

			arrIndex = $.inArray(unescape(cleanedLocation), arrayOfWork);

			if (arrIndex == -1) {

				return false;

			} else {

				location = arrayOfWork[arrIndex + direction];

				if (!location) {

					return false;
				}

				splitstring = location.split(/\?/);
				location = splitstring[0];
				query = splitstring[1];

				var returnedLocation = [location, query];

				if (loadorcheck == 'check') {

					return returnedLocation;

				} else {
					quietLoadSection(returnedLocation[0], unescape(returnedLocation[1]));

				}

				controlNavHighlighting(currentLocation);

			}
		}
		return false;
	}



	function renderSectionLanding(ourUrl, ourQuery) {
		$('h1').hide();
		//console.log('renderSectionLanding(' + ourUrl + ', ' + ourQuery +')');
		var nextLocation;
		currentItem = 0;

		currentLocation = ourUrl + '?' + ourQuery;

		$.ajax({
			type: 'POST',

			url: ourUrl,
			data: ourQuery,
			beforeSend: function() {
				htmlContent = '';
				subNavContent = '';
				$('#main_content').empty().show();

				$('<div class="loading_div" style="position: absolute; top: 0; left:0;"><img src="../img/anibar.gif" height="2" width="10" /></div>').appendTo('#main_content');
			},
			success: function(htmldata) {
				htmlContent = $(htmldata).find('div.section_container');
				subNavContent = $(htmldata).find('div#subnavs_container');
			},
			complete: function() {

				

				var imageInfo;

				$(htmlContent).find("li .image_container").attr("style", "display:none");
				$(htmlContent).appendTo('#main_content');

				$('#subnavs_container').empty();

				$(subNavContent).appendTo('#subnavs_container').fadeIn(300);

				$('.image_info').hide();

				imageInfo = $('.gallery ul li').eq(currentItem).find('.image_info');

				$(imageInfo[0]).clone().appendTo('#info_container').hide();

				manageItemDescriptions($('.gallery ul li').eq(currentItem));

				$('#main_content').show();

				if ($('.gallery ul li').length == 1) {

					$('.gallery ul li').eq(currentItem).removeClass().addClass('onlychild');

					renderNext.list = $('.gallery ul li .image_container img').eq(currentItem).get();
					renderNext();

					getLocation(unescape(currentLocation), 1, 'load');

					singleImageLoad = true;

				} else {
					renderNext.list = $('.gallery ul li .image_container img').slice(currentItem, (currentItem + 2)).get();
					renderNext();
				}

				controlNavHighlighting(unescape(currentLocation));

				handleScale(newWidth, newHeight);

				if (ourUrl == '/commissioned.php') {
					pageSizing(true);
				} else {
					pageSizing();
				}
				bindNextPrevToImages(currentItem);

			}

		});

		if (($(window).height() < 760) && (ourUrl == '/commissioned.php')) {
			$('#footer').hide();
		}
		return false;
	}



	function generateImagePagination() {
		////////console.log('generateImagePagination');
		if (!handheld) {

			var nextprevHTML;
			nextprevHTML = '<div id="next_prev_container"><ul><li id="next_img">Next</li><li id="prev_img">Previous</li></ul></div>';
			$('#next_prev_container').remove();

			$(nextprevHTML).appendTo('#nav_container #info_container');

			$('#nav_container #info_container').fadeIn(300);

			if (currentLocation == '/news') {
				$('#info_container .image_info').attr('style', 'height: 85px');
			}
		}

		return false;

	}



	function manageItemDescriptions(ourElement) {
		////////console.log('manageItemDescriptions(' + ourElement + ')');
		if (!handheld) {

			var imageInfo = $(ourElement).find('.image_info');
			$('#info_container .image_info').remove();
			$(imageInfo).clone().appendTo('#info_container').hide();
			$('#info_container .image_info').show();
			generateImagePagination();
		}
		return false;
	}



	function paginationNext() {
		////////console.log('paginationNext()');
		navigationShowHide();

		if ((currentLocation == '/news.php') || (currentLocation.search('/film') != -1) || (currentLocation == '/index.php')) {
			paginationBasicNext();
			return false;
		}

		if (singleImageLoad) {
			$('.gallery ul li').eq(currentItem + 1).find('.image_container').fadeIn(600, function() {

				singleImageLoad = false;
				paginationNext();

				return false;

			});

		} else {

			if ($('.gallery ul li').eq(currentItem).hasClass('last_item')) {

				singleImageLoad = true;
				paginationNext();

				return false;

			}

		}

		var checkItem = $('.gallery ul li .image_container').eq(currentItem + 1);

		if (($(checkItem).css('display') == 'none') || ($(checkItem).css('opacity') == 0) || ($('.gallery ul li').eq(currentItem + 1).hasClass('loading_container'))) {
			//////console.log('issue');
			return false;
		}

		var newLocation = '';

		var checklocations = getLocation(unescape(currentLocation), 1, 'check');

		if (checklocations == true) {

			newLocation = checklocations[0] + '?' + checklocations[1];

		}

		if ((currentItem + 1) >= $('.gallery ul li').length) {

			return false;

		}

		currentItem = currentItem + 1;

		$('.gallery_contain').scrollTo($(".gallery ul li").eq(currentItem), 300, {
			easing: 'easeInOutSine',
			onAfter: function() {
				if (!handheld) {
					$('#nav_container').animate({
						width: '140px'
					},
					300, function() {
						$('#top_level_nav, #subnavs_container, #info_container').fadeIn(300);
						navigationShowHide();
					});
				}
				manageItemDescriptions($(".gallery ul li").eq((currentItem)));

				renderNext.list = $('.gallery ul li .image_container img').slice(currentItem, (currentItem + 2)).get();
				renderNext();

				if ((currentItem + 1) >= $('.gallery ul li').length) {

					getLocation(currentLocation, 1, 'load');

				}

				controlNavHighlighting('fromPagination');

				bindNextPrevToImages(currentItem);

			}
		});

		return false;
	}



	function paginationBasicNext() {
		////////console.log('paginationBasicNext()');
		navigationShowHide();
		var numItems = $('.gallery ul li').length;

		if ((currentItem + 1) < numItems) {
			$('.gallery_contain').scrollTo($(".gallery ul li").eq(currentItem + 1), 300);
			currentItem = currentItem + 1;
			manageItemDescriptions($(".gallery ul li").eq((currentItem)));

			renderNext.list = $('.gallery ul li .image_container img').slice(currentItem, (currentItem + 2)).get();
			renderNext();

			controlNavHighlighting('fromPagination');
		}
		return false;
	}



	function paginationPrev() {
		////////console.log('paginationPrev');	
		navigationShowHide();

		if ((currentLocation == '/news.php') || (currentLocation.search('/film') != -1) || (currentLocation == '/index.php')) {
			paginationBasicPrev();
			return false;
		}

		currentItem = currentItem - 1;

		if (currentItem == -1) {

			var jumpBack = getLocation(unescape(currentLocation), -1, 'check');

			if (jumpBack) {
				$('.gallery').fadeOut(300);
				renderSectionLanding(jumpBack[0], jumpBack[1]);
				currentItem = 0;
			}

		}

		if (currentItem != -1) {
			$('.gallery_contain').scrollTo($(".gallery ul li").eq(currentItem), 300, {
				onAfter: function() {
					if (!handheld) {
						$('#nav_container').animate({
							width: '140px'
						},
						300, function() {
							$('#top_level_nav, #subnavs_container, #info_container').fadeIn(300);
							navigationShowHide();
						});
					}

					manageItemDescriptions($(".gallery ul li").eq((currentItem)));
					controlNavHighlighting('fromPagination');

					if ($('.gallery ul li').eq(currentItem).attr('class') == 'onlychild') {
						$('.gallery ul li .image_container:gt(' + (currentItem) + ')').fadeOut(300);
					} else {
						$('.gallery ul li .image_container:gt(' + (currentItem + 1) + ')').hide();
					}

					bindNextPrevToImages(currentItem);

				}
			});

		}

		return false;

	}



	function paginationBasicPrev() {
		////////console.log('paginationBasicPrev()');
		navigationShowHide();
		if (currentItem >= 1) {
			$('.gallery_contain').scrollTo($(".gallery ul li").eq(currentItem - 1), 300);
			currentItem = currentItem - 1;
			manageItemDescriptions($(".gallery ul li").eq((currentItem)));
		}
		return false;
	}



	function paginationUp() {
		////////console.log('paginationUp()');
		navigationShowHide();

		var thisLocation = currentLocation.split(/\?/)[0];
		var checkthis = thisLocation.replace(".php", "");

		if (thisLocation != '/index') {

			thisLocation = $.inArray(checkthis, locationArray);

			if (thisLocation != -1) {
				getAjaxDataForLinkLocation(locationArray[thisLocation - 1]);
			}

		}

		return false;
	}



	function paginationDown() {
		////////console.log('paginationDown()');
		navigationShowHide();

		var thisLocation = currentLocation.split(/\?/)[0];
		var checkthis = thisLocation.replace(".php", "");

		if (checkthis != '/contact') {
			thisLocation = $.inArray(checkthis, locationArray);

			if (thisLocation != -1) {
				getAjaxDataForLinkLocation(locationArray[thisLocation + 1]);
			}
		}

		return false;
	}



	function controlNavHighlighting(navLocation) {
		////console.log('controlNavHighlighting(' + navLocation + ')');
		if (navLocation === '/index.php') {
			$('#top_level_nav li').each(function() {
				$(this).removeClass();
			});

			$('#home_link').addClass('selected');
			return false;
		}

		var topNavItems = $('#top_level_nav li');

		if (handheld) {
			var subNavItems = $('#mobile_sub li');
		} else {
			var subNavItems = $('.sub_nav li');
		}

		if (navLocation == 'fromPagination') {

			var paginLoc = $('.gallery ul li .image_info p .clientinfo').eq(currentItem).text();
			paginLoc = 'item=' + paginLoc;

			$(subNavItems).each(function() {

				if ($(this).find('a').attr('href')) {

					var navItem = unescape($(this).find('a').attr('href'));

					navItem = navItem.split(/\?/);

					if (navItem[1] == paginLoc) {

						currentLocation = unescape($(this).find('a').attr('href'));

						$(this).removeClass().addClass('selected');

						if (handheld) {
							$('#footer').empty();
							var appendThisToFooter = $(this).text();
							$('#info_container, #subnavs_container').empty().hide();
							$('<span>' + appendThisToFooter + '</span>').appendTo('#footer').show();

						}

					} else {

						$(this).removeClass();

						if (handheld) {
							$(this).hide();
						}

					}
				}
			});

		} else {

			$(topNavItems).each(function() {

				if ($(this).find('a').attr('href')) {

					var thisLocation = unescape($(this).find('a').attr('href'));

					if (thisLocation.charAt(0) != '/') {
						thisLocation = '/' + thisLocation; //returns base url of each item
					}

					thisLocation = thisLocation.replace('.php', '');

					thisLocation = thisLocation.split(/\?/);

					var passedLocation = navLocation.split(/\?/);
					passedLocation = passedLocation[0].replace('.php', '');

					if (thisLocation[0] == passedLocation) {
						$(this).addClass('selected');

						if (handheld) {
							var topSectionTitle = $(this).text();
							$(this).hide();
							$('#top_red_bar').empty();
							$('<span>' + topSectionTitle + '</span>').appendTo('#top_red_bar');
						}

					} else {

						$(this).removeClass();
						if (handheld) {
							$(this).hide();
						}

					};

				}

			});

			if ((navLocation == '/home') && (handheld)) {
				$('#footer').empty();
				$('.sub_nav').hide();
				return false;
			}

			if ((navLocation == '/contact') && (handheld)) {
				$('#footer').empty();
				$('.sub_nav').hide();
				return false;
			}

			if ((navLocation == '/about') && (handheld)) {
				$('#footer').empty();
				$('.sub_nav').hide();
				return false;
			}

			$(subNavItems).each(function() {

				if ($(this).find('a').attr('href')) {

					var thisLocation = unescape($(this).find('a').attr('href'));

					thisLocation = thisLocation.split(/\?/);

					var passedLocation = navLocation.split(/\?/);

					var clean = passedLocation[1].replace(/\+/g, ' ');

					////////console.log(thisLocation[1] + ' : ' + clean);
					if (thisLocation[1] == clean) {
						$(this).addClass('selected');

						if (handheld) {
							$('#footer').empty();
							var appendThisToFooter = $(this).text();
							$('#info_container, #subnavs_container').empty().hide();
							$('<span>' + appendThisToFooter + '</span>').appendTo('#footer').show();
							$('.sub_nav').hide();
						}

					} else {

						$(this).removeClass();
						if (handheld) {
							$(this).hide();
						}
					}

				}

			});

		}

		if ((navLocation == '/contact.php') || (navLocation == '/about.php')) {
			$('#nav_container #info_container, #subnavs_container ul').hide();
		}

		return false;
	}



	function mobile_getCommissioned() {
		var renderHTML;
		var ourListSort = new Array();
		$('h1').hide();

		mobile_updateNavigation('Commissioned');
		mobNavDisplayRanOnce = true;

		$('#info_container').hide();

		$.ajax({
			url: 'dgill.json',
			dataType: 'json',
			beforeSend: function() {

			},
			success: function(dgillJSON) {

				var data = dgillJSON['dgill'][0]['commissioned'];
				var dataLength = dgillJSON['dgill'][0]['commissioned'].length;
				var x = 0;

				renderHTML = '<ul class="flat_gallery">';

				for (var i = 0; i < dataLength; i++) {

					if (data[i]['mobile'] !== 'n') {

						ourListSort[x] = [data[i]['mobile'], data[i]['img_name']];

						x++;
					}

				} // end for
				ourListSort.sort(sortNumber);

				dataLength = ourListSort.length;

				////console.log(ourListSort);
				for (var i = 0; i < dataLength; i++) {

					renderHTML += '<li><div class="image_container" style="display:none"><img src="images/thumbs/' + ourListSort[i][1] + '" width="295" /></div></li>';

				}

				renderHTML += '</ul>';

			},
			complete: function() {
				$('#main_content').empty();
				$(renderHTML).appendTo('#main_content');

				$('#main_content').fadeIn(300);

				renderNext.list = $('.flat_gallery li .image_container img').get();
				renderNext();

			}
		});

		return false;
	}



	function mobile_getNonCommissioned() {

		var renderHTML;
		var ourListSort = new Array();
		$('h1').hide();

		mobile_updateNavigation('Non-Commissioned');

		mobNavDisplayRanOnce = true;

		$('#info_container').hide();

		$.ajax({
			url: 'dgill.json',
			dataType: 'json',
			beforeSend: function() {

			},
			success: function(dgillJSON) {

				var data = dgillJSON['dgill'][1]['non-commissioned'];
				var dataLength = dgillJSON['dgill'][1]['non-commissioned'].length;
				var x = 0;

				renderHTML = '<ul class="flat_gallery">';

				for (var i = 0; i < dataLength; i++) {

					if (data[i]['mobile'] !== 'n') {

						ourListSort[x] = [data[i]['mobile'], data[i]['img_name']];

						x++;
					}

				} // end for
				ourListSort.sort(sortNumber);

				dataLength = ourListSort.length;

				//				//////console.log(ourListSort);
				for (var i = 0; i < dataLength; i++) {

					renderHTML += '<li><div class="image_container" style="display:none"><img src="images/thumbs/' + ourListSort[i][1] + '" width="295" /></div></li>';

				}

				renderHTML += '</ul>';

			},
			complete: function() {
				$('#main_content').empty();
				$(renderHTML).appendTo('#main_content');

				$('#main_content').fadeIn(300);

				renderNext.list = $('.flat_gallery li .image_container img').get();
				renderNext();

			}
		});

		return false;
	}



	function mobile_getFilm() {
		////////console.log('mobile_getFilm ()');
		$('h1').hide();

		mobile_updateNavigation('Film');
		mobNavDisplayRanOnce = true;

		$('#info_container').hide();

		var renderHTML;

		$.ajax({
			url: 'dgill.json',
			dataType: 'json',
			beforeSend: function() {
				//nothing here.
			},
			success: function(dgillJSON) {

				var data = dgillJSON['dgill'][2]['film'];
				var dataLength = dgillJSON['dgill'][2]['film'].length;

				renderHTML = '<ul class="flat_gallery">';

				for (var i = 0; i < dataLength; i++) {

					renderHTML += '<li><iframe src="' + data[i]["url"] + '?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="295" height="165" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></li>';

				} // end for
				renderHTML += '</ul>';

			},
			complete: function() {

				$('#main_content').empty();
				$(renderHTML).appendTo('#main_content');
				$('#main_content').show();
				$('.flat_gallery li').hide();
				$('.flat_gallery li').each(function(i) {
					$(this).delay(1000 * i).fadeIn(300);
				});

			}

		});

		return false;
	}



	function mobile_getNews() {
		$('h1').hide();

		mobile_updateNavigation('News');
		mobNavDisplayRanOnce = true;

		$('#info_container').hide();

		var renderHTML;

		$.ajax({
			url: '/news.php',
			beforeSend: function() {
				htmlContent = '';
				$('#main_content').empty();
				$('<div class="loading_div" style="position: absolute; top: 0; left:0;"><img src="../img/anibar.gif" height="2" width="10" /></div>').appendTo('#main_content');
				//$('#info_container').empty();
			},
			success: function(htmldata) {
				renderHTML = $(htmldata).find('div.section_container .gallery');
				////////console.log(renderHTML);
				$(renderHTML).appendTo('#main_content');
				$('.gallery').removeClass('gallery').find('ul').addClass('flat_gallery');

				$('.loading_div').hide();
			},
			complete: function() {
				$('#main_content').fadeIn(300, function() {

				});
			}
		});

		return false;
	}



	function mobile_getAbout() {
		$('h1').hide();

		mobile_updateNavigation('About');
		mobNavDisplayRanOnce = true;

		$('#info_container').hide();

		var renderHTML;

		$.ajax({
			url: '/about.php',
			beforeSend: function() {
				htmlContent = '';
				$('#main_content').empty();

				//$('#info_container').empty();
			},
			success: function(htmldata) {
				renderHTML = $(htmldata).find('div.section_container');

				////////console.log(renderHTML);
				$(renderHTML).appendTo('#main_content');
				$('.loading_div').hide();
			},
			complete: function() {
				$('#main_content').fadeIn(300, function() {

				});
			}
		});

		return false;
	}



	function mobile_getContact() {
		$('h1').hide();

		mobile_updateNavigation('Contact');
		mobNavDisplayRanOnce = true;

		$('#info_container').hide();

		var renderHTML;

		$.ajax({
			url: '/contact.php',
			beforeSend: function() {
				htmlContent = '';
				$('#main_content').empty();
				$('<div class="loading_div" style="position: absolute; top: 0; left:0;"><img src="../img/anibar.gif" height="2" width="10" /></div>').appendTo('#main_content');
				//$('#info_container').empty();
			},
			success: function(htmldata) {
				renderHTML = $(htmldata).find('div.section_container');
				////////console.log(renderHTML);
				$(renderHTML).appendTo('#main_content');

				$('.loading_div').hide();
			},
			complete: function() {
				$('#main_content').fadeIn(300, function() {

				});
			}
		});

		return false;
	}



	function mobile_getHome() {

		if (($('#top_red_bar').css('display') == 'none') || ($('#top_red_bar').css('opacity') == 0) || ($('#top_red_bar').is(":empty"))) {

			$('#top_red_bar').hide();
			$('#top_level_nav').show();
			$('#top_level_nav #home_link').hide();

		}

		$('#top_red_bar').attr('height', '0px');

		$('#info_container').hide();

		$('#main_content').empty();

		return false;
	}



	function mobile_updateNavigation(section, override) {

		if (override) {
			$('#top_red_bar').empty();
			$('<span>Film</span>').appendTo('#top_red_bar');
		}

		if (mobNavDisplayRanOnce) {
			return false;
		}

		//$('<span></span>').appendTo('#top_red_bar');
		$('#top_red_bar').attr('style', 'height: 0px; padding-top: 8px;');
		$('#top_red_bar').show();

		$('#top_level_nav li').each(function() {

			var checkTitle = $(this).find('a').text();

			if (checkTitle === section) {

				$(this).removeClass().addClass('selected');

				$('#top_red_bar').empty();
				$('<span>' + section + '</span>').appendTo('#top_red_bar');
				$('#top_red_bar span').hide();

				$('#top_level_nav li').delay(3500).fadeOut(150, function() {
					$('#top_red_bar').attr('style', 'height: 12px; padding-top: 8px;');
					$('#top_red_bar span').show();
					$('#top_level_nav li.selected').removeClass();
					mobNavDisplayRanOnce = true;
				});

			}

		});

		$('#top_level_nav').show();

		//		}
		return false;
	}



	function sortNumber(a, b) {
		return a[0] - b[0];
	}

}); //end doc.ready

