/**
 * Javascript particular to the Gallery on the 
 * Choose Your Way Bellevue Site
 **/

	if(typeof PLY == 'undefined') var PLY = {};
	
	/**
	 * Site Related Display Settings
	 **/
	PLY.Settings = {
		/**
		 * Controls the speed of Gallery Fades. 
		 * Can be normal, fast, slow or a millisecond integer value 
		 **/
		GalleryFadeSpeed 				: 'normal',
		/**
		 * Controls the interval on which the Gallery gets
		 * auto-rotated.
		 **/
		GalleryAutoRotationInterval		: 8000
	}
	
	/**
	 * PLY Utilities Namespace
	 **/
	PLY.Utilities = {
		/**
		 * PLY ImageLoader
		 **/
		ImageLoader : {
            Images : [],
            LoadImageSet : function(arrImagePaths, callback) {
                if(typeof arrImagePaths == 'string') arrImagePaths = [ arrImagePaths ];
                var _imageCount = arrImagePaths.length;
                var _loadedImageCount = 0;
                $.each(arrImagePaths, function(index, strImagePath) {
                    if(PLY.Utilities.ImageLoader.GetImage(strImagePath) == null) {
                        var objImage = new PLY.Utilities.Image(strImagePath);
                        PLY.Utilities.ImageLoader.Images.push(objImage);
                        objImage.$image.load(function() {
                            _loadedImageCount++;
                            if(_loadedImageCount == _imageCount && typeof callback == 'function')
                                callback();
                        });
                    } else {
                        _imageCount--;
                        if(_imageCount == 0 && typeof callback == 'function') callback();
                    }
                });
            },
            IsImageLoaded : function(strImagePath) {
                if(typeof strImagePath != 'string') return false;
				$image = PLY.Utilities.ImageLoader.GetImage(strImagePath);
				if($image != null) {
                	return PLY.Utilities.ImageLoader.GetImage(strImagePath).isLoaded;
				} else {
					return false;
				}
            },
            GetImage : function(strImagePath) {
                var _image = null;
                $(PLY.Utilities.ImageLoader.Images).each(function(index, objImage) {
                    if(objImage.strPath == strImagePath) _image = objImage;
                });
                return _image;
            }
        },
		/**
		 * Image Class
		 **/
        Image : function(strPath) {
            var _this = this;
            this.strPath = (strPath ? strPath : '');
            this.isLoaded = false;
            this.$image = $('<img>').attr('src', _this.strPath);
            this.$image.load(function() {
                _this.isLoaded = true;
            });
        },
		/**
		 * Helper function to get the height of the "More Info"
		 * containers, which are absolutely positioned.
		 *
		 * @param {jQuery} The jQuery Extended Element.
		 *
		 * @param {Integer} The height of the element.
		 **/
		GetPhotoBoxAbsoluteElementHeight : function($element) {
			$eleParent	= $element.parent();
			$element 	= $element.clone();
			$($eleParent).append($('<div>').attr('id', 'hiddenSizeBox').css({ 'height' : '0px', 'visibility' : 'hidden', 'width' :  $eleParent.outerWidth(), 'overflow' : 'hidden' }));
			$eleSizeBox = $('#hiddenSizeBox');
			$($eleSizeBox).append($element.css({ 'position' : 'relative', 'height' : 'auto' }));
			$intEleHeight = $element.outerHeight();
			$eleSizeBox.remove();
			return $intEleHeight;
		}
	}

	/**
	 * PLY UI Namespace
	 **/
	PLY.UI = {
		/**
		 * Custom PLY Gallery built for the Choose Your Way Bellevue
		 * homepage.
		 *
		 * @author: Sam Skjonsberg
		 **/
		Gallery : function(hshOptions) {
			// Reference for Object Instance within callback function() {} scope.
			var _this = this;
			/* Class Variables */
			this.$imageContainer 	 	= $(hshOptions.imageContainerCssSelector);	
			this.$titleContainer		= $(hshOptions.titleContainerCssSelector);
			this.$descContainer			= $(hshOptions.descContainerCssSelector);
			this.$arrButtons		 	= $(hshOptions.buttonCssSelector);				
			this.arrData				= [];			
			this.strLoadingImagePath   	= '/media/cob/images/icons/loading.gif';
			this.intLoadingImageHeight 	= 32;
			this.intLoadingImageWidth  	= 32;			
			this.intActiveItemIndex		= 0;
			this.isPaused				= false;
			
			/**
			 * Display the Next Gallery Item in the sequence.  Starts over
			 * upon reaching the end of the gallery item collection.
			 *
			 * @return {void}
			 **/
			this.DisplayNextGalleryItem = function() {
				var intNextItemIndex = this.intActiveItemIndex + 1;
				if(intNextItemIndex >= this.arrData.length) {
					intNextItemIndex = 0;
				}
				this.DisplayGalleryItem(intNextItemIndex);
			}
			
			/**
			 * Display the Gallery Item at the specified index, if it exists.
			 * 
			 * @param {Integer} intIndex Required The index of the item to display.
			 *
			 * @return {void}
			 **/
			this.DisplayGalleryItem = function(intIndex) {
				if(typeof this.arrData[intIndex] != 'undefined' && intIndex != this.intActiveImageIndex) {
					// Current Image
					var $curImage 			= _this.$imageContainer.find('img');
					// Next Image
					var strNextImagePath 	= _this.arrData[intIndex].path;
					var strNextImageDesc 	= _this.arrData[intIndex].desc;
					var strNextImageTitle 	= _this.arrData[intIndex].title;
					// Start the process of hiding the current one and showing the next
					$curImage.fadeOut(PLY.Settings.GalleryFadeSpeed, function() {
						$curImage.remove();
						// Check if we've already loaded the next image, if not show the loading
						// graphic and load it, once its done loading show it.
						if(!PLY.Utilities.ImageLoader.IsImageLoaded(strNextImagePath)) {
							$loadingImage = PLY.Utilities.ImageLoader.GetImage(_this.strLoadingImagePath).$image;
							strLeftMargin = ( parseInt(_this.$imageContainer.width(), 10) - _this.intLoadingImageWidth ) / 2;
							strTopMargin  = ( parseInt(_this.$imageContainer.height(), 10) - _this.intLoadingImageHeight ) / 2;
							$loadingImage.css({
								'margin-left' : strLeftMargin + 'px',
								'margin-top'  : strTopMargin + 'px'
							});
							_this.$imageContainer.append($loadingImage);
							PLY.Utilities.ImageLoader.LoadImageSet([ strNextImagePath ], function() {
								$loadingImage.remove();
								$nextImage = PLY.Utilities.ImageLoader.GetImage(strNextImagePath).$image;
								_this.renderNewItem($nextImage, strNextImageTitle, strNextImageDesc);
							});
						} else {
							$nextImage = PLY.Utilities.ImageLoader.GetImage(strNextImagePath).$image;
							_this.renderNewItem($nextImage, strNextImageTitle, strNextImageDesc);						
						}					
						// Set the active button
						_this.SetActiveButton(intIndex);
						_this.intActiveItemIndex = intIndex;	
					});
				}
			}
			
			this.SetActiveButton= function(intIndex) {
				if(typeof _this.$arrButtons[intIndex] != 'undefined') {
					_this.$arrButtons.filter('.active').removeClass('active');
					$(_this.$arrButtons[intIndex]).addClass('active');
				}
			}
			
			// Get the Data for the Gallery, from a hidden container
			var arrImagePathsToLoad = [ this.strLoadingImagePath ];
			jQuery.each($(hshOptions.dataCssSelector), function(i, ele) {
				var strImagePath = $(ele).find('.imagePath').text();
				_this.arrData.push({
					'title' : $(ele).find('.imageTitle').html(),
					'desc'	: $(ele).find('.imageDesc').html(),
					'path'	: strImagePath
				});
				arrImagePathsToLoad.push(strImagePath);
			});
			
			// Start preloading the images related to the gallery
			PLY.Utilities.ImageLoader.LoadImageSet(arrImagePathsToLoad);
			
			// Setup Click Events for the numbered (1, 2, 3) buttons
			// which switch out the photo, title, and description on click.
			jQuery.each(this.$arrButtons, function(index, eleButton) {
				$(eleButton).click(function() {
					// Do nothing if you're already active
					if($(this).hasClass('active')) { return false; }
					_this.DisplayGalleryItem(index);
					// Reset the rotation interval
					_this.startRotationInterval();					
				});
			});
			
			/**
			 * Handles updating the image, description, and title.
			 **/
			this.renderNewItem = function($objImage, strTitle, strDescription) {
				this.hideAboutBox();
				$objImage.hide();
				this.$imageContainer.append($objImage);
				this.$titleContainer.html(strTitle);
				$objImage.fadeIn(PLY.Settings.GalleryFadeSpeed, function() {
					_this.$descContainer.html(strDescription);
				});
			}
			
			/**
			 * Handles automatic image rotation.
			 **/
			this.startRotationInterval = function() {
				if(this.interval)
				{
					clearInterval(this.interval);
				}
				this.interval = setInterval(
					function() {
						if(!_this.isPaused)
							_this.DisplayNextGalleryItem();
					},
					PLY.Settings.GalleryAutoRotationInterval
				);
			}
			
			/**
			 * Hides the About Box.
			 **/
			this.hideAboutBox = function() {
				$('#aboutBox').animate({'height' : '0px'}, function() {
					$('#moreInfo').find('.button').text('+');
					$('#moreInfo').find('a').text('More Info');
					_this.isPaused = false;
				});
			}
						
		}
	}
	
	$(document).ready(function() {
		// Setup the Gallery
		var Gallery = new PLY.UI.Gallery({
			'imageContainerCssSelector' : '#photoBox',
			'buttonCssSelector'			: '#imgButtons div.button',
			'dataCssSelector'			: '#photoBoxData span.imageSet',
			'titleContainerCssSelector' : '#photoBox #titleBox',
			'descContainerCssSelector'	: '#photoBox #aboutBox #aboutContentWrapper'
		});
		// show description
		$('#moreInfo, #photoBox .photoClick').click(function() {
			$aboutBox = $('#aboutBox');
			$button	  = $('#moreInfo');
			if(parseInt($aboutBox.css('height'), 10) == 0) {
				eleHeight = PLY.Utilities.GetPhotoBoxAbsoluteElementHeight($aboutBox);
				Gallery.isPaused = true;
				$aboutBox.animate({'height' : eleHeight }, function() {
					$button.find('.button').text('-');
					$button.find('a').text('Hide');
				});
			} else {
				$aboutBox.animate({'height' : '0px'}, function() {
					$button.find('.button').text('+');
					$button.find('a').text('More Info');
					Gallery.isPaused = false;
				});
			}
		});
		// Rotate Gallery Images on a Timer
		Gallery.startRotationInterval();
	});
