(function(window, jQuery, undefined) {
    window.FLINT = window.FLINT || {};
    window.FLINT.lmff = window.FLINT.lmff || {};

    window.FLINT.lmff.gallery = {
        init: function(imgArray) {
            this.imgArray = imgArray;

            this.generateThumbnails()
                .delegateEvents()
                .handleKeys()
                .autoNavigateToSlideshowBasedOnQueryString();
        },
        generateThumbnails: function() {
            var self = this,
                $sidebarLinks = $('#nav a.gallery'),
                randomHeights = [130, 180, 190, 210, 220, 230],
				$thumbnail,
				$output;

			this.isSingleGallery = this.imgArray.length === 1;

            this.$gallery = $('<div class="gallery clearfix' + (this.isSingleGallery ? ' single-gallery' : '') + '" />');

            this.$slideshowOverlay = $('<div class="slideshow-overlay" />').appendTo(this.$gallery);
            this.$slideshowWrapper = $('<div class="slideshow-wrapper clearfix" />').appendTo(this.$gallery);

            this.$column1 = $('<div class="column column1" />').appendTo(this.$gallery);
            this.$column2 = $('<div class="column column2" />').appendTo(this.$gallery);
            this.$column3 = $('<div class="column column3" />').appendTo(this.$gallery);

            $.each(this.imgArray, function(index){
                var randomHeight = randomHeights[Math.floor(Math.random()*randomHeights.length)],
                    $outputColumn,
                    $thumbnailInner,
                    $img;

                switch ((index + 1) % 3) {
                    case 1:
                        $outputColumn = self.$column1;
                        break;
                    case 2:
                        $outputColumn = self.$column2;
                        break;
                    case 0:
                        $outputColumn = self.$column3;
                        break
                }

                if (this.photos) {
                    $thumbnail = $('<div class="thumbnail" data-gallery-id="' + this.id + '"></div>');
                    $thumbnailInner = $('<div class="thumbnail-inner" data-height="' +randomHeight + '"></div>').appendTo($thumbnail);
                    $img = $('<img src="admin-resources/image-tools.php?src=' + this.photos[0].file + '&w=203&h=300&c=1&q=85" width="203" height="300" />').appendTo($thumbnailInner);

                    $outputColumn.append($thumbnail);

                    $thumbnailInner.css({height: $thumbnailInner.attr('data-height')});

                    //Handle matching sidebar link events
                    $sidebarLinks.eq(index).mouseover(function(){
                        $thumbnail.addClass('thumbnail-hover');
                    }).mouseout(function(){
                        $thumbnail.removeClass('thumbnail-hover');
                    }).click(function(event){
                        $thumbnail.click();
                        event.preventDefault();
                    });

                    //Store the gallery data against the thumbnail
                    //This is used to populate the slideshow later
                    $thumbnail.data('slideshowData', this);

					if (self.isSingleGallery) {
						$thumbnail.hide();
					}
                }
            });

            $output = this.imgArray[0].$output || $('#pageContent');

			if (this.imgArray[0].$output === undefined && $output.children('div.contentFull').length === 1) {
				$output = $output.children('div.contentFull');
			}

			$output.append(this.$gallery);

			if (this.isSingleGallery) {
				this.openSlideshow($thumbnail);
			}

            return this;
        },
        delegateEvents: function() {
            var self = this;

            this.$gallery.delegate("div.thumbnail", "click", function(){
                self.openSlideshow($(this));
            }).delegate("div.slideshow-overlay", "click", function(){
                self.closeSlideshow();
            }).delegate("div.slideshow-photo", "click", function(){
                self.activatePhoto($(this));
            }).delegate("div.slideshow-back", "click", function(){
                self.closeSlideshow();
            }).delegate("div.slideshow-next", "click", function(){
                self.nextPhoto();
            }).delegate("div.slideshow-prev", "click", function(){
                self.prevPhoto();
            });

            return this;
        },
        handleKeys: function() {
            var self= this;
            
            $(document).keydown(function(event){
                var key = event.which;
                if (key === 37) { //Left
                    self.prevPhoto();
                } else if (key === 39) { //Right
                    self.nextPhoto();
                } else if (key === 27 | key === 38) { //Esc or Up
                    if (!self.isSingleGallery) {
						self.closeSlideshow();
					}
                }
            });

            return this;
        },
        openSlideshow: function($clickedThumbnail) {
            var self = this,
				marginTop,
                scrollTop;

            //If the slideshow is already open, close it and pass a callback to open the new slideshow
            if (this.$activeSlideshow != null) {
                this.closeSlideshow(function(){
                    self.openSlideshow($clickedThumbnail);
                });
                //Cancel out of the function -- it will be called again by the previous callback
                return;
            }

            this.$activeThumbnail = $clickedThumbnail;
            this.$activeSlideshow = null;

            //Retrieve the slideshow info and its collection of photo titles and URLs
            this.slideshowData = this.$activeThumbnail.data('slideshowData');

            //Fade in slideshow wrapper (starts off small, then resizes later)
            this.$slideshowWrapper.css({
                marginTop: 0,
                left: $clickedThumbnail.position().left,
                top: $clickedThumbnail.position().top,
                width: $clickedThumbnail.outerWidth(),
                height: $clickedThumbnail.outerHeight()
            }).fadeIn(this.isSingleGallery ? 0 : 200);

            if (this.$activeThumbnail.position().top > $(document).height() - 800) {
                //Thumbnail is near the bottom of the page
                marginTop = -638 + $clickedThumbnail.outerHeight();
                scrollTop = $clickedThumbnail.offset().top + $clickedThumbnail.outerHeight()
                    - 684 //Height of the slideshow + fixed header
                    - ($(window).height() > 900 ? 10 : 0) //If the window is taller than 900px, give an extra 10px of breathing space at the top
                    + (window.onorientationchange !== undefined ? 35 : 0); //If on a mobile device, adjust for the lack of a fixed header
            } else {
                marginTop = 0;
                scrollTop = $clickedThumbnail.offset().top
                    - 46 //Height of fixed header + padding
                    - ($(window).height() > 900 ? 10 : 0) //If the window is taller than 900px, give an extra 10px of breathing space at the top
                    + (window.onorientationchange !== undefined ? 35 : 0); //If on a mobile device, adjust for the lack of a fixed header
            }

            //Fade in white backdrop...
            this.$slideshowOverlay.fadeTo(this.isSingleGallery ? 0 : 200, .9, function(){
                //Then scroll to thumbnail...
                $('html,body').animate({scrollTop: self.isSingleGallery ? 0 : scrollTop}, self.isSingleGallery ? 0 : 600, "swing", function(){
                    //Then resize slideshow wrapper...
                    self.$slideshowWrapper.animate({
                        height: 638,
                        left: 0,
                        marginTop: marginTop,
                        width: '100%'
                    }, self.isSingleGallery ? 0 : 600, 'easeInOutExpo', function() {
                        //Then, finally, generate the slideshow
                        self.generateSlideshow();
                    });
                });
            });
        },
        generateSlideshow: function() {
            if (this.$activeSlideshow != null) {
                return;
            }

            //Generate all the nested slideshow elements
            var $slideshow = $('<div class="slideshow" />'),
                $photoWrapper = $('<div class="photo-wrapper" />').appendTo($slideshow),
                $photoScroller = $('<div class="photo-scroller clearfix" />').appendTo($photoWrapper),
                $slideshowControls = $('<div class="slideshow-controls">' + (this.isSingleGallery ? '' : '<div class="slideshow-back"><span>&lt;&lt;&lt;</span>Back to list</div>') + '<div class="slideshow-prev"><span>&lt;&lt;&lt;</span> Back</div><div class="slideshow-next">Next <span>&gt;&gt;&gt;</span></div></div>').appendTo($slideshow),
                $photoTitle = $('<div class="photo-title">' + this.slideshowData.photos[0].title + (this.slideshowData.photos[0].linkUrl === undefined ? '' : '<a href="' + this.slideshowData.photos[0].linkUrl + '">&raquo;&raquo;&raquo; ' + this.slideshowData.photos[0].linkTitle + '</a>') + '</div>').appendTo($slideshowControls);
			
            //Add the image credits, if required
            if (this.slideshowData.showCredits === 1 || this.slideshowData.showCredits === true) {
                $('<div class="slideshow-credits"><strong><span class="text-image">Image </span>Credits</strong>Lucas Dawson<br /><span class="text-contact">Contact: </span><a href="http://www.lucasdawson.com.au" target="_blank">www.lucasdawson.com.au</a> </div>').appendTo($slideshowControls);
			}

            //Loop through all the photos in the gallery
            $.each(this.slideshowData.photos, function(index){
                if (this != '') {
                    var photoUrl = 'admin-resources/image-tools.php?src=' + this.file + '&w=370&p=1&q=85',
                        $photo = $('<div class="slideshow-photo' + (index === 0 ? ' first' : ' inactive') + '"><div class="hover-overlay"></div></div>')
                            .css({
                                'background-image': 'url("' + photoUrl + '")',
                                'z-index': 999 - index //Cascade the z-index backwards
                            });

                    //Set the first photo as the active photo
                    if (index === 0) {
                        self.$activePhoto = $photo;
                    }

                    $photoScroller.append($photo);
                }
            });

            $slideshow.appendTo(this.$slideshowWrapper).fadeIn(this.isSingleGallery ? 0 : 500);
            this.$activePhoto = $photoScroller.children(':first');
            
            //Slide in the photos one by one
            $photoScroller.children().each(function(index){
                var $this = $(this);
                setTimeout(function(){
                    $this.animate({
                        'margin-left': 0
                    }, 400, 'swing');
                }, 800 * (index + 1));
            });

            //Store references in the gallery module for later
            this.$activeSlideshow = $slideshow;
            this.$photoScroller = $photoScroller;
            this.$photoTitle = $photoTitle;
        },
        activatePhoto: function($photo) {
            var self = this,
                photoIndex = $photo.index(),
                activePhotoIndex = this.$activePhoto.index(),
                marginLeft;

            //Cancel if they've clicked the active image or if it's currently animated
            if (photoIndex === activePhotoIndex || this.$photoScroller.is(':animated')) {
                return;
            }

            $photo.removeClass('inactive');
            this.$activePhoto.stop(true,true).addClass('inactive');

            //Calculate the left margin for $photoScroller
            if (photoIndex === 0) {
                //The user has clicked the first image
                marginLeft = 0
            }
            else if (photoIndex > activePhotoIndex) {
                //The user has clicked a photo after the currently active photo
                marginLeft = ($photo.position().left * -1) + this.$activePhoto.width() - 48;
            } else {
                //The user has clicked a photo before the currently active photo
                marginLeft = ($photo.position().left * -1);
            }

            //Slide the $photoScroller container using the previously calculated value so the clicked photo is on the left
            this.$photoScroller.stop(true,true).animate({
                'margin-left': marginLeft
            }, 500, 'easeInOutExpo');

            //Shrink the currently active photo
            this.$activePhoto.stop(true,true).animate({
                width: 48
            }, 500, 'easeInOutExpo');

            //Enlarge the clicked photo
            $photo.stop(true,true).animate({
                width: 361
            }, 500, 'easeInOutExpo')

            //Replace the currently displayed title
            this.$photoTitle.fadeOut(200, function(){
                $(this).html(self.slideshowData.photos[photoIndex].title + (self.slideshowData.photos[photoIndex].linkUrl === undefined ? '' : '<a href="' + self.slideshowData.photos[photoIndex].linkUrl + '">&raquo;&raquo;&raquo; ' + self.slideshowData.photos[photoIndex].linkTitle + '</a>')).fadeIn(200);
            });

            this.$activePhoto = $photo;
        },
        nextPhoto: function() {
            if (this.$activeSlideshow != null) {
                this.activatePhoto(this.$activePhoto.next().length ? this.$activePhoto.next() : this.$photoScroller.children(':first'));
            }
        },
        prevPhoto: function() {
            if (this.$activeSlideshow != null) {
                this.activatePhoto(this.$activePhoto.prev().length ? this.$activePhoto.prev() : this.$photoScroller.children(':last'));
            }
        },
        closeSlideshow: function(callback) {
            var self = this;

            if (this.$activeSlideshow === null) {
                return;
            }

            this.$activeSlideshow.fadeOut(200, function(){
                $(this).remove();

                self.$activeSlideshow = null;

                self.$slideshowWrapper.animate({
                    marginTop: 0,
                    left: self.$activeThumbnail.position().left,
                    top: self.$activeThumbnail.position().top,
                    width: self.$activeThumbnail.outerWidth(),
                    height: self.$activeThumbnail.outerHeight()
                }, 600, 'easeInOutExpo', function() {
                    if (typeof callback === 'function') {
                        setTimeout(callback, 300);
                    }

                    self.$slideshowOverlay.fadeOut(200);
                    self.$slideshowWrapper.fadeOut(200);
                });
            });
        },
        //Verbose name, but accurate ;)
        autoNavigateToSlideshowBasedOnQueryString: function() {
            function getQuerystring(key, default_) {
              var default_ = default_ || undefined;
              key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
              var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
              var qs = regex.exec(window.location.href);
              if(qs == null)
                return default_;
              else
                return qs[1];
            }

            var galleryId = getQuerystring('galleryId');
            if (galleryId !== undefined) {
                this.$gallery.find('div[data-gallery-id=' +galleryId + ']').click();
            }
        }
    };
})(this,jQuery);

/*// grab the flash gallery as an object, declare GalleryId
var galleryId
var flashMovie;

$(document).ready(function() {
    
    flashMovie = document.getElementById('Gallery');
    
    $('a.gallery').each(function() {
    	var results = $(this).attr('href').match(/([\d]+)$/);
    	var id = results[0];	
    	$(this).hover(function() {
            flashMovie.rolloverGalleryId(id);
    	}, function() {
            flashMovie.rolloutGalleryId(id);
    	});
    	$(this).click(function(e) {
    	    e.preventDefault();
    		// To my flash pass the ID
    		$('a.gallery').removeClass('selected');
    		$(this).addClass('selected');
            flashMovie.updateGalleryId(id);
    	});
    });
   // $('#pageFooter').hide();
    
    
      

    
    
    
    
});



function resetHeight(height) {
    $('#flashGallery').css({height: height+30});
    $('#flashGallery embed').attr('height', height+30);
}

function goToByScroll(position){
    position = position+102;
    $('html,body').stop(true, true);
    $('html,body').animate({scrollTop: position}, 600, "swing");
}*/
