"use strict";

function deleteArrayItem(sourceArray, index) {
	if (index === 0) {
		return sourceArray.pop();
	} else if (index === sourceArray.length - 1) {
		return sourceArray.push();
	} else {
		var returnArray = sourceArray.slice(0, index);
		return returnArray.concat(sourceArray.slice(index + 1));
	};
};

function addUniqueToArray(destArray, value) {
	var varFound = 0, r = 0;

	for (r = 0; r < destArray.length; r++) {
		varFound = 0;
		if (value === destArray[r]) {
			varFound = 1;
			break;
		};
	};
	
	if (varFound === 0) {
		destArray[destArray.length] = value;
	};
	return destArray;
};

function fileNameFromPath(fileName, delimiter) {
	fileName = fileName.split(delimiter);
	var name = fileName[fileName.length - 1].split('.')[0];
	return name;
};

function getCenterCoords($item, $parentItem) {

	var top = 0, left = 0;
	$parentItem.outerHeight() ? top = (($parentItem.outerHeight() - $item.outerHeight()) / 2) : top = (($parentItem.height() - $item.outerHeight()) / 2);
	$parentItem.outerWidth() ? left = (($parentItem.outerWidth() - $item.outerWidth()) / 2) : left = (($parentItem.width() - $item.outerWidth()) / 2);
	return {
		'left': left + 'px',
		'top': (top + $(document).scrollTop()) + 'px'
	};
};

function centerContent($content, $parentContainer) {
	var coords = getCenterCoords($content, $parentContainer);
	$content.css({
		'position': 'absolute',
		'left': coords.left,
		'top': coords.top
	});
};

var INTROGALLERY = {
	"container": "",
	"containerName": "",
	"urlBase": "",
	"url":	"",
	"domain": "atlas",
	"activePanel": 1,
	"activeItem": "",
	"panelWidth": 0,
	"panelHeight": 0,
	"panels": '',
	"slideDuration": 6000,
	"slideShow": false,
	"slideShowStatus": "stopped",
	"slideTimer": false,
	"slideNavControls": true,
	"slideNavControlOpacity": 0.15,
	"slideDirection": "left",
	"slideTransitioning": false,
	"transitionTime": 500,
	"easingType": "swing",
	"imageResolution": "720",
	"imageSizeRatio": 0,
	"items": false,
	"itemsIncludeHTML": false,
	"compareItems": null,
	"loadCounter": 0,
	"showItemNameStatus": false,
	"showNavTip": true,
	"hideNavArrowsDelay": 1000,
	"scrollArrowsTimer": '',
	"displayThumbNails": false,
	"clear": function () {
		// CLEAR FUNCTION USED TO RESET GALLERY TO DEFAULTS
		// USED PRIOR TO LOADING IN NEW DEFAULTS VIA INIT()
	
		// REMOVE ALL PANELS
		var _introGallery = this;
		if (!_introGallery.url) {
		
			_introGallery.url = '';
			_introGallery.urlBase = '';
		
			// CLEAR THE CONTENTS OF THE GALLERY
			$(_introGallery.container).children().remove();
			$('#thumbNails').remove();
		}
		_introGallery.activePanel = 1;
		_introGallery.activeItem = '';
		_introGallery.panelWidth = 0;
		_introGallery.panelHeight = 0;
		_introGallery.imageResolution = '720';
		_introGallery.items = false;
		_introGallery.itemsIncludeHTML = false;
		_introGallery.loadItems = true;
		_introGallery.loadCounter = 0;
		_introGallery.showItemNameStatus = false;

		if (!$('.loading')) {
			$('<div class="loading"></div>').appendTo('body');
		}
		
		// REMOVE ANY EXISTING NAV MESSAGE - A NEW ONE MAY BE LOADED
		// DEPENDING ON HOW THE GALLERY IS INITIALIZED
		$('#navMessage').remove();

	},
	"init": function(initVariables, callback) {
		//MASTER INITIALIZATION FUNCTION
		
		var _introGallery = this;
		
		// ASSIGN INITIAL VARIABLES
		_introGallery.urlBase = initVariables.urlBase;
		_introGallery.url = initVariables.url;

		// DISABLE RIGHT CLICK ON PANEL IMAGES AND THUMBNAILS
		$('#bodycontents').delegate('.panelImage, .thumbImage', 'contextmenu', function(e) {
			e.preventDefault();
		});
		
		
		// CLEAR EXISTING CONTENTS AND VARIABLES
		_introGallery.clear();
		_introGallery.containerName = initVariables.containerName;
		_introGallery.container = '#' + _introGallery.containerName;
		
		// OPTIONAL STARTUP VALUES
		if (initVariables.detectResolution != undefined) {
			_introGallery.detectResolution = initVariables.detectResolution;
		}
		if (initVariables.slideShow != undefined) {
			_introGallery.slideShow = initVariables.slideShow;
		}
		if (initVariables.showItemNameStatus != undefined) {
			_introGallery.showItemNameStatus = initVariables.showItemNameStatus;
		}
		if (initVariables.transitionTime != undefined) {
			_introGallery.transitionTime = initVariables.transitionTime;
		}
		if (initVariables.easingType != undefined) {
			_introGallery.easingType = initVariables.easingType;
		}
		if (initVariables.showNavTip != undefined) {
			_introGallery.showNavTip = initVariables.showNavTip;
		}
		if (initVariables.displayThumbNails != undefined) {
			_introGallery.displayThumbNails = initVariables.displayThumbNails;
		}
		
		// DISPLAY NAVIGATION TIPS MESSAGE - BASE MESSAGE ON SLIDESHOW STATUS
		if (_introGallery.showNavTip) {
			var navTipFile = '';
			if(_introGallery.slideShow) {
				navTipFile = '/htmlresources/messages/navMessage-Slideshow.html';
			} else {
				navTipFile = '/htmlresources/messages/navMessage-Manual.html';
			};

			$.get(navTipFile, function(data) {
				$('#bodycontents').append(data);
				
				$('#navMessageRight, #navMessageLeft').click(function() {
					_introGallery.advanceSlide($(this).text());
				})
				
				// HANDLE THE CLOSE NAVIGATION TIP BUTTON
				$('#navTipCloseBtn').click(function() {
					_introGallery.hideNavMessage();
				});
				
				$('#navMenuSpan').click(function() {
					NAVIGATION.menuClick();
				});
			});
		};
		
		var $container = $(_introGallery.container);
		
		$(window).resize(function() {
			_introGallery.resize();
			$('.panelImage').each(function() {
					_introGallery.resizeImage($(this));
				});
			});

		//ADD THUMBNAILS HTML TO PAGE
		if (_introGallery.displayThumbNails) {
			$('<div id="thumbNails"></div>').appendTo('#bodycontents');
			$('<div id="thumbNailIcon"><img src="/img/thumbnail-icon.png"/></div>').appendTo('#bodycontents');
			$('<div id="thumbCloseIcon"><img src="/img/closeicon.png"/></div>').appendTo('#bodycontents');
			$('background-mask').fadeIn('fast');
		};
		
		if (_introGallery.detectResolution) {
			_introGallery.getsize();
		};
		if (_introGallery.url) {
			_introGallery.load();
		} else {
			_introGallery.parsePreLoaded();
			_introGallery.displayPreLoaded();
		};
		
		// START SLIDESHOW AND HANDLE THE PLAY/PAUSE BUTTON
		// OR SHOW NAV SIDE PANEL GRAPHICS AS NAVIGATIONAL TIP
		if (_introGallery.slideShow) {
			var $navSlideShowControls = $('#navSlideShowControls');
			$navSlideShowControls
				.css('display', 'block')
				.animate({'opacity': _introGallery.slideNavControlOpacity}, 6000)
				.hover(function() {
					$(this)
						.stop(true, true)
						.animate({'opacity': 1}, 'fast');
				}, function() {
					$(this)
						.stop(true, true)
						.animate({'opacity': _introGallery.slideNavControlOpacity}, 'slow');
				});

			// HANDLE PLAY BUTTON HOVER
			$navSlideShowControls
				.children()
				.eq(1)
				.hover(function() {
					if (_introGallery.slideShowStatus == 'running') {
						$(this).attr('src', '/img/mhp-pausebutton-hover.png');
					} else {
						$(this).attr('src', '/img/mhp-playbutton-hover.png');
					};
				}, function() {
					if (_introGallery.slideShowStatus == 'running') {
						$(this).attr('src', '/img/mhp-pausebutton.png');
					} else {
						$(this).attr('src', '/img/mhp-playbutton.png');
					};
				});
			
			// HANDLE ADVANCE BUTTON HOVER
			$navSlideShowControls
				.children()
				.eq(2)
				.hover(function() {
					$(this).attr('src', '/img/mhp-advanceonebutton-hover.png');
				}, function() {
					$(this).attr('src', '/img/mhp-advanceonebutton.png');
				});
			
			// HANDLE PREVIOUS BUTTON HOVER
			$navSlideShowControls
				.children()
				.eq(0)
				.hover(function() {
					$(this).attr('src', '/img/mhp-backonebutton-hover.png');
				}, function() {
					$(this).attr('src', '/img/mhp-backonebutton.png');
				});
				
			// HANDLE PLAY BUTTON CLICK
			$navSlideShowControls
				.children()
				.eq(1)
				.click(function() {
					if (_introGallery.slideShowStatus == 'running') {
						_introGallery.stopSlideShow();
					} else if (_introGallery.slideShowStatus == 'stopped') {
						_introGallery.startSlideShow();
					};
				});
			
			// HANDLE ADVANCE BUTTON CLICK
			$navSlideShowControls
				.children()
				.eq(2)
				.click(function() {
					if (_introGallery.slideShowStatus == 'running') {
						_introGallery.stopSlideShow();
						_introGallery.advanceSlide('left');
						_introGallery.startSlideShow();
					} else {
						_introGallery.advanceSlide('left');
					};
				});
			
			// HANDLE PREVIOUS BUTTON CLICK
			$navSlideShowControls
				.children()
				.eq(0)
				.click(function() {
					if (_introGallery.slideShowStatus == 'running') {
						_introGallery.stopSlideShow();
						_introGallery.advanceSlide('right');
						_introGallery.startSlideShow();
					} else {
						_introGallery.advanceSlide('right');
					};
				});
			
		};		
		
		// EXECUTE A CALLBACK FUNCTION AT END OF INITIALIZATION
		if (callback && typeof(callback) === 'function') {
			var callBackInterval = setInterval(function() {
				if (_introGallery.items.length == + _introGallery.loadCounter) {
					clearInterval(callBackInterval);
					callback();
				}
			}, 250);
		};

	},
	"getsize": function() {
		// USE BROWSER HEIGHT TO DETERMINE WHAT RESOLUTION IMAGES TO LOAD
		var _introGallery = this;
		if ($(window).height() > 900 && _introGallery.imageResolution != '1080') {
			_introGallery.imageResolution = '1080';
			_introGallery.url = _introGallery.urlBase + '/' + '1080/1080.json';
		} else if ($(window).height() > 500) {
			_introGallery.imageResolution = '720';
			_introGallery.url = _introGallery.urlBase + '/' + '720/720.json';
		} else {
			_introGallery.imageResolution = '360';
			_introGallery.url = _introGallery.urlBase + '/360/360.json';
		};
	},
	"load": function() {
		// LOAD A JSON DOCUMENT WITH GALLERY INFO FROM THE URL PASSED IN THE INIT SECTION
		var _introGallery = this;

		$.ajax({
			"dataType": "json",
			"type": "get",
			"url": _introGallery.url,
			"reset": function() {},
			"beforeSend": function() {},
			"complete": function() {},
			"success": function(data) {
				_introGallery.loadItems = false;
				_introGallery.items = data.results;
				for (var i=0; i < _introGallery.items.length; i++) {
					if (_introGallery.items[i].type == 'html') {
						_introGallery.itemsIncludeHTML = true;
						break;
					}
				}
				_introGallery.display(_introGallery.items);
			},
			"error": function(xhr, status) {
				alert(status);
			}
		});
	},
	"display": function(itemList) {
		// BUILD THE DISPLAY STRUCTURE NEEDED TO DISPLAY THE IMAGES CONTAINED IN THE JSON FILE LOADED
		var _introGallery = this;
		_introGallery.loadCounter = 0;
		
		if (_introGallery.displayThumbNails) {
			_introGallery.buildThumbContainers();
		};
		
		if (itemList.length === 0) {
			return
		};
		
		var $container = 
			$(_introGallery.container)
			.css({"width": ($(window).width() * itemList.length) + "px"});
						
		var $list = $('<div id="' + _introGallery.containerName + '"></div>');

		// MAKE THE PANELS THAT WILL HOLD THE CONTENT - FOR IMAGE PANELS, INSERT LOADING GRAPHIC
		var $panel = '';
		var $contents = '';
		var fileName = '';
		$.each(itemList, function(index, item) {
			if (item.type == 'jpg' || item.type == 'png') {
				$panel = $('<div class="panel clickTarget" id="p' + index + '"></div>')
					.append('<div class="smallLoading" id="loading-' + index + '"><p>A moment please ... loading ...</p><img src="' + item.thumbURL + '" /><p><img src="/img/ajax-loader.gif"/></p></div>')
					.append('<div class="itemName">' + fileNameFromPath(item.url, '/') + '</div>');
				$list.append($panel);
				item.loaded = false;
				// BUILD THUMBNAIL FOR THIS IMAGE
				if (_introGallery.displayThumbNails) {
					_introGallery.createThumbNail(index);
				};
			} else if (item.type == 'html') {
				$panel = $('<div class="panel" id="p' + index + '"></div>')
					.append('<div class="textClickTarget"></div>');
				$contents = $('<div class="textPanel"></div>')
					.load(item.url, function() {
						_introGallery.loadCounter++;
					})
					.appendTo($panel);
				$list.append($panel);
				item.loaded = true;
			};
			
		});
		$container.replaceWith($list);
			
		_introGallery.showItemNames(_introGallery.showItemNameStatus);

		// HERE WE BIND A CUSTOM EVENT TO THE GALLERY CONTAINER (JUST BECAUSE THAT WAS A HANDY ITEM)
		// THIS EVENT WILL CLONE THE FIRST AND LAST PANELS FOR ENDLESS SCROLLING, BUT WILL ONLY
		// DO SO IF THERE IS MORE THAN ONE ITEM IN THE GALLERY AND THE LOAD COUNTER == THE ITEM COUNT
		
		$container.bind('contentLoaded', function(e) {
			if (_introGallery.items[0].loaded === true && _introGallery.items[_introGallery.items.length-1].loaded === true) {
				clearInterval(cloneTimer);
				if (itemList.length > 1) {
					_introGallery.clonePanels();
				};
				_introGallery.panelScroll();
				_introGallery.resize();
				if (_introGallery.showNavTip) {
					_introGallery.displayNavMessage();
				};
				
				// NOW THAT EVERYTHING HAS BEEN LOADED, MAKE THE THUMBNAILS CLICKABLE AND HIDE THEM
				if (_introGallery.displayThumbNails) {
					$('#thumbNails')
						.delegate('img', 'click', function() {
							_introGallery.activePanel = parseInt($(this).attr('id').split('-')[1]) + 1;
							_introGallery.activeItem = $(this).attr('src');
							// PRELOAD CONTENT FOR NEXT SETS OF SLIDES
							_introGallery.hideThumbNails();
							_introGallery.setSlide(_introGallery.activePanel);
						});

					$('.thumbContainer').addClass('clickable');
						
					$('#thumbCloseIcon').click(function() {
						_introGallery.hideThumbNails();
					});
					
					_introGallery.hideThumbNails();
				};
				
				// NOW THAT EVERYTHING HAS BEEN LOADED, START THE SLIDESHOW
				if (_introGallery.slideShow) {
					_introGallery.startSlideShow();
				};
				
				// AFTER A TIMEOUT, SHOW THE SCROLL ARROWS AS A NAVIGATIONAL TIP
				_introGallery.scrollArrowsTimer = setTimeout(function() {
					_introGallery.showScrollArrows();
				}, 6500);
			};
		});
		
		// THIS SETTIMEOUT WILL TRIGGER THE CONTENTLOADED EVENT EVERY 325 MILISECONDS UNTIL
		// THE EVENT IS ABLE TO CLONE THE PANELS
		var cloneTimer = setInterval(function() {
			$container.trigger('contentLoaded');
		}, 325);

		// SET ACTIVE ITEM AFTER DISPLAY
		_introGallery.activeSlideUpdate();

		// LOAD PANEL CONTENTS
		_introGallery.panels = $('.panel');
		_introGallery.resize();
		_introGallery.fillPanels([0,1,2,_introGallery.items.length - 1]);
					
	},
	"fillPanels": function(panelIndexArray) {
		// LOAD THE CONTENT FOR PARTICULAR PANELS
		var _introGallery = this;
		var $panel = '';
		var $img = '';
		
		if (_introGallery.url == '') {
			return;
		}
		
		for (var i = 0; i <= panelIndexArray.length - 1; i++) {
		
			if (panelIndexArray[i] == 'undefined' || panelIndexArray[i] > _introGallery.items.length) {
				return;
			};
		
			// CONTINUE ON TO NEXT ITEM IF THIS ONE IS UNDEFINED, ALREADY LOADED OR IS IN THE PROCESS OF LOADING
			if (!(_introGallery.items[panelIndexArray[i]] == 'undefined') && !(_introGallery.items[panelIndexArray[i]].loaded === true) && !(_introGallery.items[panelIndexArray[i]].loaded === 'loading')) {
				$panel = $(_introGallery.panels[panelIndexArray[i]]);

				// SET LOADED STATUS OF THIS IMAGE
				_introGallery.items[panelIndexArray[i]].loaded = 'loading';

				$img = $('<img />')
					.attr('id', 'panelImage-' + panelIndexArray[i])
					.hide()
					.load(function() {

						_introGallery.resizeImage($(this));	
						_introGallery.loadCounter++;

						// REMOVE THE LOADING GRAPHIC
						$(this)
							.siblings('.smallLoading')
							.fadeOut('slow', function() {
								$(this).remove();
							});

						// SET LOADED STATUS OF THIS IMAGE TO TRUE
						_introGallery.items[
							$(this)
								.parent()
								.attr('id')
								.slice(1)
							].loaded = true;

						$(this)
							.fadeIn('slow');
						//_introGallery.insertImage($(this).parent().attr('id').slice(1));
					})
					.attr('class', 'panelImage')
					.attr('src', _introGallery.items[panelIndexArray[i]].url)

				$panel.append($img);

				if ($img[0].complete) {
					_introGallery.insertImage(panelIndexArray[i]);
				};
				
			};
		};
	},
	"insertImage": function(imageIndex) {
		var _introGallery = this;
		var $img = $('#panelImage-'+imageIndex);
		if ($img[0] == undefined) {
			return;
		}
		if ($img[0].complete) {
			// REMOVE THE LOADING GRAPHIC
			$img
				.siblings('.smallLoading')
				.fadeOut('slow', function() {
					$(this).remove();
				});

			// SET LOADED STATUS OF THIS IMAGE TO TRUE
			_introGallery.items[imageIndex].loaded = true;
			_introGallery.resizeImage($img);
			$img.fadeIn('slow');
		}
	},
	"clonePanels": function() {
		// CLONE THE FIRST AND LAST PANELS FOR INFINITE SCROLLING
		var _introGallery = this;
		var $firstPanel = $(_introGallery.container + ' .panel:first');
		var $lastPanel = $(_introGallery.container + ' .panel:last');

		$lastPanel
			.clone()
			.insertBefore($firstPanel)
			.attr('id', (_introGallery.items.length - 1) + '-clone');

		$firstPanel
			.clone()
			.insertAfter($lastPanel)
			.attr('id', '0-clone');
						
	},
	"parsePreLoaded": function() {
		// PARSE GALLERY INFORMATION NOT LOADED BY JSON, BUT CONTAINED IN THE .HTML FILE
		// THIS FILE NEEDS TO BE PARSED INTO A JAVASCRIPT OBJECT WHICH MATCHES THE JSON OBJECT SO THE REST
		// OF THE CODE WILL WORK WITH IT.
		var _introGallery = this;
		_introGallery.items = [];
		var _preLoadItems = $(_introGallery.container + ' .panel');
		var thumbURL = '';
		var pathArray = '';
		
		_preLoadItems.each(function(index, item) {
			_introGallery.items[index] = {};
			if($(item).children().eq(0).hasClass('panelImage')) {
				_introGallery.items[index].url = $(item).children().eq(0).attr('src');
				_introGallery.items[index].type = "jpg";
				_introGallery.items[index].loaded = false;
				
				pathArray = _introGallery.items[index].url.split('/');
				thumbURL = _introGallery.items[index].url.split('/');
				thumbURL.pop();
				thumbURL.pop();
				thumbURL = thumbURL.join('/') + '/360/' + pathArray[pathArray.length - 1];
				_introGallery.items[index].thumbURL = thumbURL;
			} else {
				_introGallery.items[index].url = "n/a";
				_introGallery.items[index].type = "html";
				_introGallery.items[index].loaded = true;
			};
		});
		_introGallery.loadCounter = _introGallery.items.length;
		if (_introGallery.items.length == 1) {
			_introGallery.hideScrollArrows();		
		}
	},
	"displayPreLoaded": function() {
		//PERFORM THE FORMATTING NEEDED TO DISPLAY GALLERY EMBEDDED IN THE HTML FILE
		var _introGallery = this;
		var $panelImages = $('.panelImage')
		
		_introGallery.showItemNames(_introGallery.showItemNameStatus);
		_introGallery.panels = $('.panel');
		_introGallery.panelIndex = 0;

		var $container = $(_introGallery.container);
		if (_introGallery.displayThumbNails) {
			_introGallery.buildThumbContainers();
		};
		if (_introGallery.showNavTip) {
			_introGallery.displayNavMessage();
		};
		
		// SET ACTIVE ITEM AFTER DISPLAY
		_introGallery.activeSlideUpdate();
		
		// DISABLE RIGHT CLICK ON IMAGES IN SLIDESHOW
		$panelImages.bind("contextmenu", function(e) {
			e.preventDefault();
		});

		_introGallery.resize();
		
		_introGallery.panels.each(function(index) {
			$(this).attr('id', 'p'+index);
		});
		
		$panelImages.each(function(index) {
			
				//ADD A LOADING ICON
				$(this).before('<div class="smallLoading"></div>');
				
				//ASSIGN THE PANEL IMAGE ID
				$(this).attr('id', 'panelImage-' + index);
					
				// BUILD THUMBNAIL FOR THIS IMAGE
				if (_introGallery.displayThumbNails) {
					_introGallery.createThumbNail(index);
				};
				
				if ($(this)[0].complete) {
					_introGallery.insertImage(index);
				}			
			})
			.load(function() {
			
				// EXECUTE WHEN THE IMAGE HAS FINISHED LOADING
				// RESIZE IMAGE FOR SCREEN
				_introGallery.resizeImage($(this));
				
				// SET ITEM'S LOADED PROPERTY
				_introGallery.items[
					$(this).attr('id').split('-')[1]
				].loaded = true;
				
				// REMOVE THE LOAD ICON
				$(this)
					.prev()
					.fadeOut('slow')
					.remove();
			});
		
		if (_introGallery.items.length > 1) {
			_introGallery.clonePanels();
		};
		
		_introGallery.panelScroll();
		_introGallery.resize();
		// PRELOADED PAGES HAVE A LOADING PAGE IN THEM TO GIVE THE SYSTEM TIME TO RESIZE IMAGES FOR DISPLAY
		$('.loading').fadeOut('slow');
			
		// MAKE THE THUMBNAILS CLICKABLE AND HIDE THEM
		if (_introGallery.displayThumbNails) {
			$('#thumbNails')
				.delegate('img', 'click', function() {
					_introGallery.activePanel = parseInt($(this).attr('id').split('-')[1]) + 1;
					_introGallery.activeItem = $(this).attr('src');
					_introGallery.resize();
					_introGallery.hideThumbNails();
				})
				.fadeOut('slow');

			$('.thumbContainer').addClass('clickable');
				
			$('#thumbCloseIcon').click(function() {
				_introGallery.hideThumbNails();
			});
			
			_introGallery.hideThumbNails();
		};

		// WHEN THE FIRST PANEL HAS COMPLETED LOADING, START THE SLIDESHOW
		$panelImages.eq(0).load(function() {
			$('.loading').fadeOut('slow');
			if (_introGallery.slideShow) {
				_introGallery.startSlideShow();
			};
		});
		
		setTimeout(function() {
			if (_introGallery.items.length > 1) {
				_introGallery.showScrollArrows();
			}
		}, 6500);
			
	},
	"resize": function() {
		// RESIZE THE PANELS WHICH COMPOSE THE GALLERY SO THAT THEY FILL THE BODY OF THE GALLERY.
		var _introGallery = this;
		var ratio = '';
		
		// SET THE WIDTH OF THE GALLERY CONTAINER TO THE HEIGHT OF THE BODY AND BODY WIDTH*NUMBER OF PANELS
		// JUMP TO SLIDE IF IN MIDDLE OF ANIMATION
		var $container = 
			$(_introGallery.container)
			.stop(true, true)
			.css({
				'width': ($('body').width()*_introGallery.items.length) + 'px',
				'height': $(window).height() + 'px'}
			);

		// SET THE WIDTH OF THE PANELS CONTAINING THE IMAGES TO THE DIMENSIONS OF THE WINDOW
		var $panels = $(_introGallery.container + ' .panel');
		$panels.css({
			'width': parseInt($('body').width()) + 'px',
			'height': parseInt($(window).height()) + 'px',
			'position': 'absolute', 'top': '0px'
		});
		
		_introGallery.panelWidth = parseInt($(window).width());
		_introGallery.panelHeight = parseInt($container.css('height'));
		
		// SET THE POSITION OF THE PANELS BASED ON THE WIDTH OF THE PANEL * IT'S POSITION IN THE LIST
		$panels
			.each(function(index) {
				if (index == 0) {
					$(this).css({
						'top': '0px',
						'left': '0px',
						'right': _introGallery.panelWidth + 'px'
					});
				} else {
					$(this).css({
						'top': '0px',
						'left': (index*_introGallery.panelWidth) + 'px',
						'right': ((index*_introGallery.panelWidth) + _introGallery.panelWidth) + 'px'
					});
				};
			});
				
		// BECAUSE THE TEXT PANELS AND IMAGE PANELS ARE DIFFERENT SIZES, WE INDIVIDUALLY CENTER THE TEXT PANELS
		var $textPanels = $(_introGallery.container + ' .textPanel');
		var coords = getCenterCoords($textPanels.filter(':first'), $textPanels.parent());
		$textPanels.css({
			'position': 'absolute',
			'top': coords.top,
			'left': coords.left
		});
		
		// NOW SET THE LEFT VALUE OF THE GALLERY CONTAINER SO THAT THE CORRECT POSITION IS MAINTAINED
		// REMEMBER WE ARE DEALING IN PIXEL VALUES OF 0 AND BELOW FOR POSITIONING SO WE NEED TO HAVE
		// A LEFT VALUE OF A NEGATIVE NUMBER ... *-1
		if (_introGallery.items.length > 1) {
			$container.css({
				'position': 'absolute',
				'top': '0px',
				'left': ((_introGallery.activePanel*_introGallery.panelWidth) * -1) + 'px'
				});
		} else {
			$container.css({
				'position': 'absolute',
				'top': '0px',
				'left': '0px'
				});
		};

	},
	"resizeImage": function($img) {
		// RESIZE A PARTICULAR IMAGE TO FILL THE SCREEN, MAINTAINING ASPECT RATIO.
		var _introGallery = this;
		var ratio = '';
		var coords = '';
		ratio = ($img.width()/$img.height()).toFixed(6);
		/*
		if (_introGallery.panelHeight*ratio > $(window).width()) {
			$img.css({'width': _introGallery.panelWidth + 'px', 'height': _introGallery.panelWidth/ratio + 'px'});
		} else {
			$img.css({'height': _introGallery.panelHeight + 'px', 'width': _introGallery.panelHeight * ratio + 'px'});
		};
		*/
		
		if (_introGallery.panelHeight*ratio > $(window).width()) {
			$img.css({'width': _introGallery.panelWidth + 'px', 'height': 'auto'});
		} else {
			$img.css({'height': _introGallery.panelHeight + 'px', 'width': 'auto'});
		};
		
		// NOW TO CENTER THE IMAGES IN THE PANEL USING LEFT AND TOP FOR THE ABSOLUTELY POSITIONED IMAGE
		coords = getCenterCoords($img, $img.parent());
		$img.css({'position': 'absolute', 'top': coords.top, 'left': coords.left});
	},
	"panelScroll": function() {
		/*
			BIND CLICKS TO THE PANELS FOR MOVING IMAGES
			THE BASIC SEQUENCE IS: 
			ONLY ACTIVATE IF MORE THAN ONE PANEL OF CONTENT
			DETERMINE THE SCROLL DIRECTION BASED ON WHAT SIDE OF THE SCREEN THE USER CLICKED
			'ENDLESS SCROLLING'
				IF WE ARE AT THE LAST PANEL, SHOW THE 'FAUX' FIRST PANEL (WHICH IS AT THE END OF THE LIST)
					AND THEN JUMP TO THE REAL BEGINNING OF THE LIST
				IF WE ARE AT THE FIRST PANEL, SHOW THE 'FAUX' LAST PANEL (WHICH IS AT THE BEGINNING OF THE LIST
					AND THEN JUMP TO THE REAL END OF THE LIST
			INCREMENT/DECREMENT/SET SLIDE COUNTER AS NEEDED
		*/
		var _introGallery = this;
		var $container = $(_introGallery.container);
		$container.show();
		
		// HANDLE CLICK OF ANY DYNAMICALLY CREATED CONTENT TO ADVANCE SLIDES
		$container.delegate('.clickTarget, .textClickTarget', 'click', function(e) {
			_introGallery.advanceByClick(e);
		});
		
		// HANDLE CLICK IF USERS CLICKS ON THE NAV TABS FOR ADVANCING SLIDES
		$('#navtab-right, #navtab-left').click(function(e) {
			_introGallery.advanceByClick(e);
		})
	},
	"advanceByClick": function(e) {
		// THIS FUNCTION EVALUATES WHERE ON THE PAGE THE MOUSE WAS WHEN IT WAS CLICKED (LEFT/RIGHT OF CENTER)
		// AND ADVANCES OR RETARDS THE SLIDE BY ONE BASED ON THAT VALUE.
		var _introGallery = this;
		// ONLY EXECUTE THIS CODE FOR SCROLLING PANELS IF THERE IS MORE THAN ONE PANEL!
		if (_introGallery.items.length == 1) {
			return;
		};
		
		// DETERMINE THE DIRECTION TO SCROLL
		if (e.pageX > _introGallery.panelWidth/2) {
			// INCREMENT THE ACTIVE PANEL VALUE
			_introGallery.advanceSlide('left');
		} else {
			// DECREMENT THE ACTIVE PANEL VALUE
			_introGallery.advanceSlide('right');
		};
		
		_introGallery.hideScrollArrows();
		if (_introGallery.items.length > 1 && _introGallery.slideShowStatus != 'running') {
			_introGallery.scrollArrowsTimer = setTimeout(function() {
				_introGallery.showScrollArrows();
			}, 4500);
		};
	},
	"advanceSlide": function(direction) {
		// THIS FUNCTION ANIMATES THE POSITION OF A SLIDE BY ONE VALUE,
		// DEPENDING ON THE DIRECTION ARGUMENT PASSED (LEFT/RIGHT)
		// IT ALSO HANDLES THE INFINITE SCROLLING ASPECT OF NAVIGATION.
		var _introGallery = this;
		
		if (_introGallery.slideTransitioning == true) {
			return;
		};
		
		_introGallery.slideTransitioning = true;
		var containerPosition = null;
		var $container = $(_introGallery.container);

		if (direction == 'left') {
			_introGallery.activePanel++;
		} else {
			_introGallery.activePanel--;
		};
		
		if (_introGallery.activePanel < 1) {
			// WE ARE AT THE FIRST PANEL GOING BACKWARDS	
			// SET ACTIVE PANEL TO LAST IN LIST
			_introGallery.activePanel = _introGallery.items.length;
			
			// ANIMATE TO FAUX LAST PANEL PANEL (AKA, LAST PANEL DUPLICATE);
			$container
				.stop()
				.animate({
					'left': '0px'
				}, _introGallery.transitionTime, _introGallery.easingType, function() {
					$container.css({'left': ((_introGallery.items.length*_introGallery.panelWidth) * -1) + 'px'});
					_introGallery.slideTransitioning = false;
					if (!_introGallery.items[_introGallery.items.length - 1].loaded && !_introGallery.items[_introGallery.items.length - 1].loaded == 'loading') {
						_introGallery.fillPanels([_introGallery.items.length-1]);
					};
					// PRELOAD CONTENT FOR NEXT SETS OF SLIDES
					_introGallery.preLoadSlides();
				});
		
		} else if (_introGallery.activePanel > _introGallery.items.length) {
			// WE ARE AT THE LAST PANEL GOING FORWARD
			// RESET ACTIVE PANEL VALUE
			_introGallery.activePanel = 1;

			// WORKOUT NEW POSITION TO ANIMATE TO
			containerPosition = (((_introGallery.items.length + 1)*_introGallery.panelWidth) * -1) + 'px';
			$container					
				.stop()
				.animate({
					'left': containerPosition
				}, _introGallery.transitionTime, _introGallery.easingType, function() {
					// AFTER ANIMATION, MOVE BACK TO BEGINNING OF PANELS
					$container.css({'left': '-' + _introGallery.panelWidth + 'px'});
					_introGallery.slideTransitioning = false;
					if (!_introGallery.items[0].loaded && !_introGallery.items[0].loaded == 'loading') {
						_introGallery.fillPanels(0);
					};
					// PRELOAD CONTENT FOR NEXT SETS OF SLIDES
					_introGallery.preLoadSlides();
				});
		
		} else {
			// IF WE ARE NOT AT THE LAST PANEL, THEN ANIMATE TO THE NEXT ONE
			containerPosition = (_introGallery.activePanel * _introGallery.panelWidth * -1) + 'px';
			$container
				.stop(true, true)
				.animate({
					'left': containerPosition
				}, _introGallery.transitionTime, _introGallery.easingType, function() {
					_introGallery.slideTransitioning = false;
					if (!_introGallery.items[_introGallery.activePanel - 1].loaded && !_introGallery.items[_introGallery.activePanel - 1].loaded == 'loading') {
						_introGallery.fillPanels([_introGallery.activePanel - 1]);
					};
					// PRELOAD CONTENT FOR NEXT SETS OF SLIDES
					_introGallery.preLoadSlides();
				});
		};

		// SET ACTIVE ITEM AFTER DISPLAY
		_introGallery.activeSlideUpdate();
		
		// UPDATE DISPLAY OF FAVORITES BUTTON, IF ACTIVE
		if (FAVORITES.active) {
			FAVORITES.updateButtons();
		};
	},
	"setSlide": function(slideIndex) {
		// THIS FUNCTION WILL GO TO A SPECIFIED SLIDE.
		var _introGallery = this;
		_introGallery.activePanel = slideIndex;

		var containerPosition = (_introGallery.activePanel * _introGallery.panelWidth * -1) + 'px';
		var $container = $(_introGallery.container);
		$container
			.stop(true, true)
			.css({
				'left': containerPosition
			});
		_introGallery.slideTransitioning = false;
		if(!(_introGallery.items[_introGallery.activePanel - 1].loaded === true) && !(_introGallery.items[_introGallery.activePanel - 1].loaded === 'loading')) {
			_introGallery.fillPanels([_introGallery.activePanel - 1]);
		};

		// SET ACTIVE ITEM AFTER DISPLAY
		_introGallery.activeSlideUpdate();
		
		// PRELOAD CONTENT FOR NEXT SETS OF SLIDES
		_introGallery.preLoadSlides();
		
		// UPDATE DISPLAY OF FAVORITES BUTTON, IF ACTIVE
		if (FAVORITES.active) {
			FAVORITES.updateButtons();
		}
	},
	"preLoadSlides": function() {
		// PRELOAD THE NEXT AND PREVIOUS SLIDES, RELATIVE TO THE CURRENT POSITION
		var _introGallery = this;
		var panelIndexArray = [];
		if (!(_introGallery.activePanel - 2 < 0)) {
			panelIndexArray[panelIndexArray.length] = _introGallery.activePanel-2;
		};
		if (!(_introGallery.activePanel > _introGallery.items.length - 1)) {
			panelIndexArray[panelIndexArray.length] = _introGallery.activePanel;
		};
		_introGallery.fillPanels(panelIndexArray);
	},
	"startSlideShow": function() {
		//START THE SLIDESHOW, IF IT IS NOT ALREADY RUNNING.
		var _introGallery = this;
		_introGallery.hideScrollArrows();
		if (_introGallery.slideShowStatus == 'running') {
			return;
		};
		_introGallery.slideShowStatus = 'running';
		_introGallery.slideShowCheck = setInterval(function() {
		
			// IF THERE ARE NO ITEMS DON'T DO ANYTHING - DUH!
			if (!_introGallery.items) {
				return;
			};
			
			clearInterval(_introGallery.slideShowCheck);
			_introGallery.slideTimer = setInterval(function() {
				_introGallery.advanceSlide(_introGallery.slideDirection);
			}, _introGallery.slideDuration);
			
			// CHANGE THE IMAGE IN THE PLAY BUTTON
			$('#navSlideShowControls')
				.children()
				.eq(1)
				.attr('src', '/img/mhp-pausebutton.png');
			
		}, 500);
		
	},
	"stopSlideShow": function() {
		// STOP THE SLIDE SHOW.
		var _introGallery = this;
		clearInterval(_introGallery.slideTimer);
		clearInterval(_introGallery.slideShowCheck);
		_introGallery.slideShowStatus = 'stopped';
		
		// CHANGE THE IMAGE IN THE PLAY BUTTON
		$('#navSlideShowControls')
			.children()
			.eq(1)
			.attr('src', '/img/mhp-playbutton.png');
		
		setTimeout(function() {
			_introGallery.showScrollArrows();
		}, 2000);
	},
	"activeSlideUpdate": function() {
		// SET THE ACTIVEPANEL PROPERTY BASED ON THE CURRENTLY ACTIVE PANEL
		//(IF THE ACTIVE PANEL IS GREATER THAN THE NUMBER OF ITEMS, SET IT TO 1, IF IT IS LESS THAN 0, SET IT TO THE LAST ITEM IN THE LIST)
		var _introGallery = this;
		if (_introGallery.activePanel > _introGallery.items.length) {
			_introGallery.activePanel = 1;
		} else if (_introGallery.activePanel < 1) {
			_introGallery.activePanel = _introGallery.items.length;
		} else if (_introGallery.items.length == 0) {
			_introGallery.activePanel = 0;
		};
		_introGallery.activeItem = _introGallery.items[_introGallery.activePanel - 1].url;
	},
	"showItemNames": function(status) {
		// DISPLAY THE NAMES OF THE IMAGE FILES ON THE SCREEN.
		var _introGallery = this;
		_introGallery.showItemNameStatus = status;

		if (status) {
			$('#maincontents .panel .itemName').css({'display': 'block'});
		} else {
			$('#maincontents .panel .itemName').css({'display': 'none'});
		};
	},
	"displayNavMessage": function() {
		// SHOW THE NAVIGATIONAL TIPS MESSAGE
		// IF WE HAVE ALREADY DISPLAYED THE NAV MESSAGE IN THIS SESSION,
		// DO NOT DISPLAY IT AGAIN
		var _introGallery = this;
		if ($.cookie('displayedNavMessage')) {
			return;
		};
		$.cookie('displayedNavMessage', true, { expires: null, path: '/', domain: _introGallery.domain})
		var _introGallery = this;
		setTimeout(function() {
			if (_introGallery.items.length < 2) {
				return
			};
			$('#navMessage').animate({
				'bottom': '-15px',
			}, 2000);
			if (!_introGallery.slideShow && _introGallery.items.length > 1) {
				_introGallery.showScrollArrows();
			};
		}, '6000');
	},
	"hideNavMessage": function() {
		// HIDE THE NAVIGATIONAL TIPS MESSAGE
		$('#navMessage').animate({
			'bottom': '-1000px',
		}, 3000);
	},
	"hideScrollArrows": function(hideDelayTime) {
		// HIDE THE NAVIGATIONAL HINT SCROLL ARROWS
		var _introGallery = this;
		clearTimeout(_introGallery.scrollArrowsTimer);
		setTimeout(function() {
			$('#navtab-right, #navtab-left')
				.fadeOut('slow');
		}, hideDelayTime);
	},
	"showScrollArrows": function() {
		// SHOW THE NAVIGATIONAL HINT SCROLL ARROWS
		$('#navtab-right, #navtab-left')
			.stop()
			.fadeTo('slow', 0.15);
	},
	"buildThumbContainers": function() {
		// BUILD THE INDIVIDUAL CONTAINERS WHICH WILL HOLD THUMBNAIL IMAGES.
		var _introGallery = this;
		
		var $thumbNailsInner = $('<div id="thumbNailsInner"></div>');
		var $thumbNail = '';
		$.each(_introGallery.items, function(index, item) {
			if (item.type == 'jpg' || item.type == 'png') {
				$thumbNail = $('<div class="thumbContainer" id="thumbContainer-' + index + '"></div>').hide();
				$thumbNailsInner.append($thumbNail);
			};
		});
		
		_introGallery.thumbNailsShowing = false;

		$('#thumbNails')
			.append($thumbNailsInner)
			.scrollTop(0);
			
		$('#thumbNailIcon')
			.click(function() {
				if (_introGallery.thumbNailsShowing) {
					_introGallery.hideThumbNails();
				} else {
					_introGallery.showThumbNails();
				};
			});
		
	},
	"createThumbNail": function(thumbIndex) {
		// BUILD THE THUMBNAIL SPECIFIED - FILL THE PRE-CREATED THUMBCONTAINER
		var _introGallery = this;
		if (_introGallery.items[thumbIndex] && _introGallery.items[thumbIndex].type != 'html') {
			var $img =	$('<img />', {
						"src": _introGallery.items[thumbIndex].thumbURL,
						"class": "thumbImage",
						"id": "thumbImage-" + [thumbIndex],
						"load": function() {
							$(this).parent().fadeIn('slow');
						}
					}); 

			$('#thumbContainer-' + thumbIndex).append($img);
		};
	},
	"hideThumbNails": function() {
		// HIDE THE ENTIRE THUMBNAIL CONTAINER
		var _introGallery = this;
		_introGallery.thumbNailsShowing = false;
		$('#thumbNails')
			.stop(true, true)
			.fadeOut('slow', function() {
				$('#background-mask').fadeOut('fast');
			});
		$('#thumbCloseIcon')
			.fadeOut('slow');
	},
	"showThumbNails": function() {
		// SHOW THE ENTIRE THUMBNAIL CONTAINER
		var _introGallery = this;
		if (_introGallery.slideShow) {
			_introGallery.stopSlideShow();
		};
		$('#background-mask').fadeTo('slow', '.85');
		_introGallery.thumbNailsShowing = true;
		$('#thumbNails, .thumbContainer')
			.stop(true, true)
			.fadeIn('slow');
		$('#thumbCloseIcon').
			fadeIn('slow');
	},
	"hideNavigation": function() {
		var _introGallery = this;
		if (_introGallery.slideShow) {
			$('#navSlideShowControls, #thumbNailIcon')
				.fadeOut('slow');
			_introGallery.hideScrollArrows();
		};
	},
	"showNavigation": function() {
		var _introGallery = this;
		if (_introGallery.slideShow && _introGallery.slideShowStatus == 'running') {
			$('#navSlideShowControls').fadeTo('slow', '0.15');
			$('#thumbNailIcon').fadeTo('slow', '0.5');
		}
		if (_introGallery.slideShow == true && _introGallery.slideShowStatus === 'stopped') {
			$('#navSlideShowControls').fadeTo('slow', '0.15');
			$('#thumbNailIcon').fadeTo('slow', '0.5');
			_introGallery.showScrollArrows();
		}
	}
};

var FAVORITES = {
	"containerName": "#favorites-controlcontainer",
	"containerTemplate": "/htmlresources/favorites/favorites-controlcontainer.html",
	"configureTemplate": "/htmlresources/favorites/addName.html",
	"cgiScript": "http://atlas/webcgi/webbatch.exe?ordersys/portraitFavorites.web",
	"domain": "atlas",
	"introGalleryURL": '',
	"introGalleryURLBase": '',
	"position": "lowerLeft",
	"names": '',
	"visible": false,
	"active": false,
	"showItemNames": false,
	"activeItem": '',
	"favoriteButtons": false,
	"sessionID": '',
	"userNamePromptShowing": false,
	"viewing": "gallery",
	"loginUser": function(userName) {
		var _favorites = this;
		$.ajax({
			"dataType": "json",
			"type": "get",
			"url": _favorites.cgiScript + '+' + _favorites.sessionID + '+ssu+' + encodeURIComponent(userName),
			"reset": function() {},
			"beforeSend": function() {},
			"complete": function() {},
			"success": function(data) {

				if (data.userID == 0) {
					alert('User Name Not found sucka!');
				} else {
					$('#favorites-userName')
						.fadeOut('slow')
						.remove();
					$('#background-mask')
						.fadeOut('slow');

					_favorites.userID = data.userID;
					_favorites.userName = data.userName;
					_favorites.customerName = data.customerName;
					_favorites.albumID = data.albumID;
					_favorites.urlBase = data.urlBase;
					
					$.cookie('favorites-userID', _favorites.userID, { expires: null, path: '/', domain: _favorites.domain})
					$.cookie('favorites-userName', _favorites.userName, { expires: null, path: '/', domain: _favorites.domain})
					$.cookie('favorites-name', _favorites.customerName, { expires: null, path: '/', domain: _favorites.domain})
					$.cookie('favorites-albumID', _favorites.albumID, { expires: null, path: '/', domain: _favorites.domain})
					$.cookie('favorites-urlBase', _favorites.urlBase, { expires: null, path: '/', domain: _favorites.domain})
					
					// ONCE WE ARE LOGGED IN, LOAD FAVORITES LIST FOR USER
					_favorites.loadFavoritesList();
				};
			},
			"error": function(xhr, status) {
				alert(status);
			}
		});
	},
	"userNamePrompt": function() {
		var _favorites = this;
		if (_favorites.userNamePromptShowing) {
			return;
		};
		_favorites.userNamePromptShowing = true;
		$('#background-mask').fadeIn('slow');
		
		$.ajax({
			"dataType": "html",
			"type": "get",
			"url": '/htmlresources/favorites/login-entername.html',
			"reset": function() {},
			"beforeSend": function() {},
			"complete": function() {},
			"success": function(data) {
				$('body').append(data);
				var $userName = $('#favorites-userName');
				centerContent($userName, $('body'));
				
				$('#favorites-userNameButton').click(function() {
					_favorites.loginUser($('#favorites-userNameInput').val());		
				});
			},
			"error": function(xhr, status) {
				alert(status);
			}
		});
		
	},
	"loadFavoritesList": function() {
		var _favorites = this;
		
		;// LOAD CONTROLS INTO PAGE
		var $container = $('<div id="favorites-controlcontainer"><div id="masthead">Favorites<img src="/img/tools-gear2-small.png"></div><div>').hide();
		var $innerContainer = $('<div id="favorites-configure"><h2>Who would like this ...?</h2></div>');
		$innerContainer.append('<span><input type="button" id="viewGallery" value="Viewing All Images" class="favoriteImage"/>');

		_favorites.names = $.getJSON(_favorites.cgiScript + '+' + _favorites.sessionID + '+lc+' + _favorites.userID + '+' + _favorites.albumID, function(data) {
			_favorites.names = data.results;
			$.each(_favorites.names, function(index, item) {
				$innerContainer.append('<span><input type="button" id="' + item.id + '" value="' + item.name + '" class="left"/><input type="button" id="' + item.id + '-view" value="View" class="right"/></span>');
			});
			$container
				.append($innerContainer)
				.insertAfter('#navigation-subcontainer')
				.css({'bottom': '-' + (parseInt($container.css('height')) + 10) + 'px'})
				.fadeIn('slow');		
				
			// THE FAVORITES MASTHEAD HIDES/SHOWS THE FAVORITES LIST
			$('#masthead').toggle(function() {
				$(this).parent().animate({'bottom': '15px'});
					_favorites.visible = true;
				}, function() {
					$(this).parent().animate({'bottom': '-' + (parseInt($container.css('height')) + 10) + 'px'});
					_favorites.visible = false;
				});
					
			// HANDLE CLICK ON FAVORITES CONFIG/GEAR ICON
			$('#favorites-controlcontainer #masthead img').click(function() {
				// HARDCODED TO IMPORT SELECTED IMAGES INTO ALBUM (ALBUM IS HARDCODED TOO!)
				$.ajax({
					"dataType": "text",
					"type": "get",
					"url": _favorites.cgiScript + '+' + _favorites.sessionID + '+if+' + _favorites.userID + '+' + _favorites.albumID,
					"reset": function() {},
					"beforeSend": function() {},
					"complete": function() {},
					"success": function(data) {
						alert('Imported Favorites!');
					},
					"error": function(xhr, status) {
						alert(status);
					}
				});
				return false;
			});
			
			_favorites.bindButtons();
			_favorites.favoriteButtons = $('#favorites-configure :input');
			_favorites.updateButtons();
			
		});
	
	},
	"init": function(values) {
		var _favorites = this;
		_favorites.position = values.position;
		_favorites.active = true;

		_favorites.showItemNames = values.showItemNames;
		INTROGALLERY.showItemNames(_favorites.showItemNames);

		// GET SESSION ID FROM SERVER SO THAT WE CAN SAVE STATE DATA.
		// IF WE HAVE SAVED A COOKIE SESSION ID, USE THAT ONE.
		if ($.cookie('sessionID') == null || $.cookie('sessionID') == 'undefined') {
			$.ajax({
				"dataType": "json",
				"type": "get",
				"url": _favorites.cgiScript + '+null+gsid',
				"reset": function() {},
				"beforeSend": function() {},
				"complete": function() {},
				"success": function(data) {
					$.cookie('sessionID', data.sessionid, { expires: null, path: '/', domain: _favorites.domain});
					_favorites.sessionID = data.sessionid;
					_favorites.userNamePrompt();
				},
				"error": function(xhr, status) {
					alert(status);
				}
			});
		} else {
		
			// RELOAD LOGIN INFORMATION FROM SESSION COOKIE
			_favorites.sessionID = $.cookie('sessionID');
			_favorites.userID = $.cookie('favorites-userID');
			_favorites.customerName = $.cookie('favorites-customerName');
			_favorites.albumID = $.cookie('favorites-albumID');
			_favorites.userName = $.cookie('favorites-userName');
			_favorites.urlBase = $.cookie('favorites-urlBase');
			if (_favorites.userID == '' || _favorites.userID == null || _favorites.userID == 'undefined') {
				alert(_favorites.userID);
				_favorites.userNamePrompt();
			};
			_favorites.loadFavoritesList();
			
		};
		
		// SAVE GALLERY PATH AND URL TO SESSION STATE FILE
		$.get(_favorites.cgiScript + '+' + _favorites.sessionID + '+ssd+' + INTROGALLERY.urlBase + '+' + INTROGALLERY.url);
				
		$(window).resize(function() {
			if (_favorites.userNamePromptShowing) {
				centerContent($('#favorites-userName'), $('body'));
			};
		});
				
	},
	"showControls": function() {
		var _favorites = this;
	},
	"hideControls": function() {
		var _favorites = this;
	},
	"bindButtons": function() {
		var _favorites = this;
		;// HANDLE BUTTON CLICKS IN FAVORITES CONTAINER
		$(_favorites.containerName).delegate(':button', 'click', function(e) {
			switch ($(this).attr('id')) {
			
				case 'viewGallery':
					_favorites.viewing = 'gallery';
					INTROGALLERY.init({
						'containerName': INTROGALLERY.containerName,
						'urlBase': _favorites.introGalleryURLBase,
						'url': _favorites.introGalleryURL,
						'transitionTime': INTROGALLERY.transitionTime,
						'slideShow': false,
						'showNavTip': false
						}, function() {
							_favorites.updateButtons();
						});
				break;
			
				case 'addName':
					$('#favorites-configure .template')
						.clone()
						.val('')
						.insertBefore('#favorites-configure .template')
						.removeClass('template')
						.focus();
				break;
				
				case 'saveNames':
				break;
				
				// SAVE FAVORITES OR VIEW FAVORITES
				default:
					
					var buttonArray = $(this).attr('id').split('-');
					if (buttonArray[1]) {
						// IF A VIEW BUTTON IS CLICKED
						$.ajax({
							"dataType": "text",
							"type": "get",
							"url": _favorites.cgiScript + '+' + _favorites.sessionID + '+vf+' + _favorites.userID + '+' + _favorites.albumID + '+' + buttonArray[0] + '+null+' + INTROGALLERY.imageResolution,
							"reset": function() {},
							"beforeSend": function() {},
							"complete": function() {},
							"success": function(data) {
								// STORE A REFERENCE TO THE ORIGINAL GALLERY URLS SO THAT WE CAN USE THEM
								// WHEN THE USER SWITCHES BACK TO VIEW ALL IMAGES MODE.
								_favorites.viewing = buttonArray[0];
								_favorites.introGalleryURL = INTROGALLERY.url;
								_favorites.introGalleryURLBase = INTROGALLERY.urlBase;
								INTROGALLERY.init({
									'containerName': INTROGALLERY.containerName,
									'urlBase': _favorites.urlBase + '/' + buttonArray[0],
									'url': _favorites.urlBase + '/' + buttonArray[0] + '/' + INTROGALLERY.imageResolution + '/' + INTROGALLERY.imageResolution + '.json',
									'transitionTime': 500,
									'slideShow': false,
									'showNavTip': false
								}, function() {
									_favorites.updateButtons();
								});
								
							},
							"error": function(xhr, status) {
								alert(status);
							}
						});
					} else {
						var nameID = $(this).attr('id');
						if ($(this).hasClass('favoriteImage')) {
							var cgiMode = '+rf+';

							// REMOVE THE ACTIVE IMAGE FROM THE USERS'S FAVORITE ARRAY IN MEMORY
							if (_favorites.names[nameID].favorites.length) {
								var f = 0;
								var fName = fileNameFromPath(INTROGALLERY.activeItem, '/');
								while (f < _favorites.names[nameID].favorites.length) {
									if (_favorites.names[nameID].favorites[f] == fName) {
										break;
									};
									f++;
								};
							}
							_favorites.names[nameID].favorites = deleteArrayItem(_favorites.names[nameID].favorites, f);
							_favorites.updateButtons();
						} else {
							var cgiMode = '+sf+';
							_favorites.names[nameID].favorites = addUniqueToArray(_favorites.names[nameID].favorites, fileNameFromPath(INTROGALLERY.activeItem, '/'));
							_favorites.updateButtons();
						};
						
						// IF A NAME BUTTON IS CLICKED
						$.ajax({
							"dataType": "html",
							"type": "get",
							"url": _favorites.cgiScript + '+' + _favorites.sessionID + cgiMode + _favorites.userID + '+' + _favorites.albumID + '+' + buttonArray[0] + '+' + INTROGALLERY.activeItem,
							"reset": function() {},
							"beforeSend": function() {},
							"complete": function() {
							},
							"success": function(data) {
							},
							"error": function(xhr, status) {
								alert(status);
							}
						});
											
					};
					
				break;
				
			};
			e.preventDefault();
		});
	},
	"updateButtons": function() {
		var _favorites = this;
		_favorites.favoriteButtons.removeClass('favoriteImage');
		if (_favorites.viewing == 'gallery') {
			$('#viewGallery')
				.addClass('favoriteImage')
				.attr('value', 'Viewing All Images');
		} else {
			$('#viewGallery')
				.attr('value', 'View All Images');
		};
		var imageName = fileNameFromPath(INTROGALLERY.activeItem, '/');
		var n = 0;
		var i = 0;
		while (_favorites.names[n]) {
			i = 0;
			while(_favorites.names[n].favorites[i]) {
				if (_favorites.names[n].favorites[i] == imageName) {
					$.each(_favorites.favoriteButtons, function(index, button) {
						if ($(button).attr('id') == _favorites.names[n].id) {
							$(this).addClass('favoriteImage');
						};
					});
				};
				i++;
			};
			n++;
		};
	},
	"configure": function() {
		var _favorites = this;
		var $container = $(_favorites.containerName).children().remove();
		$container.load(_favorites.configureTemplate);
	},
	"addName": function() {
		_favorites = this;
	},
};

var NAVIGATION = {
	"closeAfterValue": 3000,
	"hideNavArrowsValue": 5000,
	"hideHeaderTimer": "",
	"hideNavArrowsTimer": "",
	"menuBlinkTimer": false,
	"showingMap": false,
	"showingEmail": false,
	"showingNavContainer": false,
	"showingMenus": true,
	"init": function() {
		var _navigation = this;
		
		/* INITIAL HIDE NAV CONTROLS */
		_navigation.hideControls(_navigation.closeAfterValue);
		_navigation.menuBlinkTimer = setInterval(function() {
			$('#navigation-menu-right').toggleClass('highlight');
		}, 3000);
		
		// KILL THE BLINKING MENU AFTER IT HAS BEEN MOUSED OVER ONCE
		$('#navigation-menu-right').click(function() {
			_navigation.menuClick();
		});
		
		/* SETUP THE MOUSEOVER/MOUSEOUT FUNCTIONS FOR THE HEADER */
		$('#navigation-left, #navigation-right, #footer')
			.hoverIntent(function() {
				$(this).stop(true);
				clearTimeout(_navigation.hideHeaderTimer);
				_navigation.showControls();
			}, function() {
				_navigation.hideControls(_navigation.closeAfterValue);
			});

		/* UPDATE FOOTER COPYRIGHT DATE WITH CURRENT YEAR */
		var curDate = new Date();
		$('#currentYear').text(curDate.getFullYear());
			
		/* HANDLE CLICK ON SECTION CONTAINER CLOSE ICON */
		$('#navigation-subcontainer').delegate('.closeicon', 'click', function() {
			$('#background-mask').fadeOut('fast');
			$(this)
				.parent()
				.fadeOut('fast')
				.css({
					'left': '-1000px',
					'display': 'block'
				});
			_navigation.showingNavContainer = false;
			$('#navigation-sectioncontainer > div').remove();
			$('#navigation-title').text('');
			$('#logo-bottom').fadeOut('fast').remove();
		});
			
		/* HANDLE THE CLICK OF TOP NAV BUTTONS */
		$('#navigation-right div').click(function() {
			var sectionHTML = $(this).attr('alt');
			if (sectionHTML != undefined) {
			
				$('#background-mask').fadeIn('fast');
				_navigation.hideControls();
				sectionHTML = '/htmlresources/sections/' + sectionHTML + '.html';

				var navSubContainer = $('#navigation-subcontainer');
				_navigation.showingNavContainer = true;
				navSubContainer.children('#navigation-sectioncontainer').load(sectionHTML);
				$('<h2>' + $(this).attr('title') + '</h2>').appendTo($('#navigation-title'));
				var coords = getCenterCoords(navSubContainer, $(window));
				navSubContainer.css({
					"left": coords.left,
					"top": coords.top
				});
				navSubContainer.fadeIn('fast', function() {
					$('<img id="logo-bottom" src="/img/mhp-logo.png"/>')
						.appendTo('body')
						.fadeIn('slow');
				});
			};
		});

		/* HANDLE THE CLICK OF ADDRESS IN FOOTER */
		$('#mapAddress').click(function() {
			_navigation.showMap();
		});
		
		/* HANDLE THE CLICK OF EMAIL IN FOOTER */
		$('body').delegate('.contactEmail', 'click', function() {
			_navigation.showEmail();
		});
		
		/* HANDLE THE CLICK OF SECTION BUTTONS IN POPUP NAV TOOLS - INTERNET EXPLORER WASN'T HONORING HREF LINKS WRAPPED AROUND BUTTONS*/
		$('#navigation-sectioncontainer').delegate('input[type="button"]', 'click', function(e){
			window.location = $(this).parent().attr('href');
			return false;
		});
		
		/* HANDLE CLICK OF CATEGORY PANEL */
		$('.categoryContainer').delegate('.categoryPanel', 'click', function() {
			var htmlPath = $(this).attr('alt');
			if (htmlPath != undefined) {
				window.location = htmlPath;
				return false;
			}
		});
		
		/* MAKE LOGO RETURN TO HOME PAGE */
		$('#logo').click(function(){
			window.location = '/index.html';
		})
		
		/* RESIZE THE CONTENT PANEL TO ACCOMODATE THE WINDOW SIZE */
		$(window).resize(function() {
			if (_navigation.showingNavContainer) {
				var navSubContainer = $('#navigation-subcontainer');
				var coords = getCenterCoords(navSubContainer, $(window))
				navSubContainer.css({
					"left": coords.left,
					"top": coords.top
				});
			};
			if (_navigation.showingMap) {
				_navigation.positionMap();
			};
			if (_navigation.showingEmail) {
				_navigation.positionEmail();
			};
		});
	},
	"menuClick": function() {
		var _navigation = this;
		/* GET RID OF THE BLINKING MENU */
		clearInterval(_navigation.menuBlinkTimer);
		$(this).addClass('highlight');
		clearTimeout(_navigation.hideHeaderTimer);

		/* HANDLE THE CLICK ON THE MENU BUTTON */
		if (_navigation.showingMenus) {
			_navigation.hideControls(0);
		} else {
			$('#header, #footer').stop(true);
			_navigation.showControls();
			_navigation.hideControls(_navigation.closeAfterValue*3);
		};
	},
	"hideControls": function(closeAfterValue) {
		var _navigation = this;

		_navigation.hideHeaderTimer = setTimeout(function() {
			/* HIDE THE HEADER */
			$('#header')
				.stop(true)
				.animate({'top': '-27px'}, 'slow', function() {
					$('#navigation-menu-right')
						.addClass('highlight');
					$(this).css('z-index', '126');
					_navigation.showingMenus = false;
				});

			
			/* HIDE THE LOGO */
			$('#logo')
				.stop(true)
				//.animate({'top': '-300px'}, 'slow');
				.animate({
					'opacity': '0.5',
					'filter': ''
					}, 'slow');
				
			/* HIDE THE FOOTER */	
			$('#footer')
				.stop(true, true)
				.fadeOut('slow');
				
			/* DISPLAY THE INTROGALLERY CONTROLS */
			INTROGALLERY.showNavigation();
		}, closeAfterValue);
	},
	"showControls": function() {
		var _navigation = this;

		/* HIDE THE INTROGALLERY CONTROLS */
		INTROGALLERY.hideNavigation();
		
		$('#header')
			.stop()
			.animate({'top': '0px'}, 'slow', function() {
				_navigation.showingMenus = true;
			});
			
		$('#logo')
			.stop()
			//.animate({'top': '0px'}, 'slow');
			.fadeTo('slow', '1.0');
			
		$('#footer')
			.stop(true, true)
			.fadeIn('slow');
	},
	"showMap": function() {
		var _navigation = this;
		
		if (_navigation.showingMap) {
			return;
		};
		
		_navigation.showingMap = true;

		$.ajax({
			"dataType": "html",
			"type": "get",
			"url": '/htmlresources/googleMaps.html',
			"reset": function() {},
			"beforeSend": function() {},
			"complete": function() {},
			"success": function(data) {
				$('#background-mask').css('display', 'block');
				$('body').append(data);
				var $closeMap = $('<img id="navMapContainerClose" src="/img/closeicon.png"/>').appendTo('body');
				_navigation.positionMap();
				$closeMap.click(function() {
					$('#navMapContainer')
						.fadeOut('slow', function() {
							$(this).remove();
							$('#background-mask').css('display', 'none');
						});
					$(this).remove();
					_navigation.showingMap = false;
				});
			},
			"error": function(xhr, status) {
				alert(status);
			}
		});
	},
	"showEmail": function() {
		var _navigation = this;
		if (_navigation.showingEmail) {
			return;
		};
		
		_navigation.showingEmail = true;
		
		var $emailContainer = $('<div id="emailContainer"></div>');
		
		$.ajax({
			"dataType": "html",
			"type": "get",
			"url": '/htmlresources/emailForm.html',
			"reset": function() {},
			"beforeSend": function() {},
			"complete": function() {},
			"success": function(data) {

				// LOAD BACKGROUND MASK AND EMAIL FORM, POSITION
				$('#background-mask').css('display', 'block');
				$emailContainer.append(data);
				$('#bodycontents').append($emailContainer);
				_navigation.positionEmail();
				
				// HANDLE CLICKS TO CLOSE EMAIL
				$('#closeEmailContainer, #emailCancelButton').click(function() {
					_navigation.hideEmail();
				});
				
				// HANDLE FORM VALIDATION
				$('#emailForm').validate({
					'debug': true,
					'rules': {
						'emailName': {
							'required': true
						},
						'emailAddress': {
							'required': true,
							'email': true
						},
						'emailSubject': {
							'required': true
						},
						'emailMessage': {
							'required': true
						}
					},
					'messages': {
						'emailName': 'What should we call you?',
						'emailAddress': {
							'required': 'We need your email address to contact you.',
							'email': 'Please enter a valid email address (name@domain.com)'
						},
						'emailSubject': 'What is your question about?',
						'emailMessage': 'What is your question?'
					},
					'success': function(label) {
					},
					'submitHandler': function(form) {
						_navigation.sendEmail();
					}
				});
				
				//HANDLE SEND EMAIL BUTTON CLICK
				$('#emailSendButton').click(function() {
					// EXECUTE THE SUBMIT ACTION FOR VALIDATION PURPOSES,
					// BUT DO NOT ACTUALLY ALLOW THE FORM TO SUBMIT.
					$('#emailForm').submit(function(e) {
						e.preventDefault;
					});
				});
				
			},
			"error": function(xhr, status) {
				alert(status);
			}
		});
	
	},
	"positionMap": function() {
		var _navigation = this;
		if (!_navigation.showingMap) {
			return;
		};
		var $iFrame = $('#navMapContainer');
		centerContent($iFrame, $('#bodycontents'));
		var leftPos = (parseInt($iFrame.css('left')) + parseInt($iFrame.css('width'))-15) + 'px';
		$('#navMapContainerClose').css({
			'left': leftPos,
			'top': (parseInt($iFrame.css('top'))-15) + 'px'
		});
	},
	"positionEmail": function() {
		var _navigation = this;
		if(!_navigation.showingEmail) {
			return;
		};
		var $emailContainer = $('#emailContainer');
		centerContent($emailContainer, $('#bodycontents'));
		/*
		$('#closeEmailContainer').css({
			'position': 'absolute',
			'right': '-15px',
			'top': '-15px'
		});
		*/
	},
	"sendEmail": function() {
		var _navigation = this;
	
		$.ajax({
			"dataType": "html",
			"type": "GET",
			"timeout": 5000,
			"url": 'http://www.michealhallphotography.com/contactmailer.php',
			"data": $('#emailForm').serialize(),
			"reset": function() {},
			"beforeSend": function() {},
			"complete": function() {},
			"success": function(data) {				
				_navigation.hideEmail();
			},
			"error": function(xhr, status, data) {
				//alert(status+' | '+data);
				_navigation.hideEmail();
			}
		
		});
	},
	"hideEmail": function() {
		var _navigation = this;
		$('#emailContainer')
			.fadeOut('slow', function() {
				$(this).remove();
			});
		$('#background-mask').fadeOut('slow');
		_navigation.showingEmail = false;
	}
};

