﻿
// Global Variables.
var flickrSlideshow = null;


(function($) {
	
	// Client-side Property Declarations.
	Artemis.Modules.Flickr.Slideshow.CreateProperty("PhotoList", []);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("PreLoadedImages", []);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("PreLoadedThumbs", []);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("SelectedFlickrID", null);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("SelectedThumb", null);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("ImageHeight", 178);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("ImageWidth", 240);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("ThumbHeight", 50);
	Artemis.Modules.Flickr.Slideshow.CreateProperty("ThumbWidth", 60);


    window["load_Artemis_Modules_Flickr_Slideshow"] = function(obj) {
        
		// Variables.
        flickrSlideshow = obj;

		var scrollbarList = null;
        var isScrolling = false;
        var changeInterval = null;
		var scrollValue = 20;    
        var scrollTimeoutValue = 20;
        


		// Event Handlers.
        $("#btnScrollRight").mousedown(function(event) {
            event.preventDefault();
                        
            $(this).addClass("active");
            
            var interval = setInterval(function() { 
                if (isScrolling)
                {
                    obj.ScrollPhotoList(scrollValue, scrollTimeoutValue);
                }
            }, scrollTimeoutValue);


			var inactiveHandler = function(event) {
				clearInterval(interval);
                $(this).removeClass("active").unbind("mouseup", inactiveHandler).unbind("mouseout", inactiveHandler);
			};

            $(this).mouseup(inactiveHandler).mouseout(inactiveHandler);
        });
                    
                    
        $("#btnScrollLeft").mousedown(function(event) {
            event.preventDefault();
                        
            $(this).addClass("active");
            
            var interval = setInterval(function() { 
                if (isScrolling)
                {
                    obj.ScrollPhotoList(scrollValue * -1, scrollTimeoutValue);
                }
            }, scrollTimeoutValue);


			var inactiveHandler = function(event) {
				clearInterval(interval);
                $(this).removeClass("active").unbind("mouseup", inactiveHandler).unbind("mouseout", inactiveHandler);
			};

            $(this).mouseup(inactiveHandler).mouseout(inactiveHandler);
        });
                    
                    
        $("#controlPanelLip").click(function(event) { 
            if ($(this).attr("class").indexOf("down") > -1)
            {
                $("#slideshowControlPanel").animate({ bottom: -52 }, 700, null, function() {
                    $("#controlPanelLip").addClass("up").removeClass("down");
                });
            }
            else
            {
                $("#slideshowControlPanel").animate({ bottom: 0 }, 700, null, function() {
                    $("#controlPanelLip").addClass("down").removeClass("up");
                });
            }
        });
                    
                    
        $(".slideshowButton").mousedown(function(event) {
            event.preventDefault();
            $(this).addClass("pressed");
        });
                    
        $(".slideshowButton").mouseup(function(event) {
            event.preventDefault();
            $(this).removeClass("pressed");
        });
                    
                    
        $("#prevButton").click(function(event) {
            event.preventDefault();
                        
            obj.SelectPreviousPhoto();
            obj.Pause();
                        
            $("#playButtonDiv").css("display", "inline");
            $("#pauseButtonDiv").css("display", "none");
        });
                    
                    
        $("#nextButton").click(function(event) {
            event.preventDefault();
                        
            obj.SelectNextPhoto();
            obj.Pause();
                        
            $("#playButtonDiv").css("display", "inline");
            $("#pauseButtonDiv").css("display", "none");
        });
                    
                    
        $("#pauseButton").click(function(event) {
            event.preventDefault();
            
            obj.Pause();
            
            $(this).parent().css("display", "none");
            $("#playButtonDiv").css("display", "inline");
        });
                    
                    
        $("#playButton").click(function(event) {
            event.preventDefault();
            
            obj.Play();
            
            $(this).parent().css("display", "none");
            $("#pauseButtonDiv").css("display", "inline");
        });



		// Functions.
        this.ScrollPhotoList = function(scrollValue, speed) { 
            var left = parseInt(scrollbarList.css("left"));
            var currentLeft = left;
            
            if (scrollValue > 0)
            {
                left = left - scrollValue;
            }
            else if (scrollValue < 0)
            {
                if (Math.abs(left) + scrollValue < 0)
                {
                    left = 0;
                }
                else
                {
                    left = left + (scrollValue * -1);
                }
            }
            else { return; }
            
            
            var items = scrollbarList.children();
            var scrollBar  = $("#slideshowScrollBar");
            
            var lastThumbnailRightEdge = items[items.length - 1].offsetLeft + (items[items.length - 1]).offsetWidth + currentLeft + (this.ThumbWidth() / 2);
            var scrollBarRightEdge = scrollBar[0].offsetLeft + scrollBar[0].offsetWidth;
            
            if (left > currentLeft)
            {
                isScrolling(true);
                scrollbarList.animate({ left: left }, speed, null, function() { isScrolling(false); });
            }
            else
            {
                if (lastThumbnailRightEdge < scrollBarRightEdge)
                {
                    if (left > currentLeft)
                    {
                        isScrolling(true);
                        scrollbarList.animate({ left: left }, speed, null, function() { isScrolling(false); });
                    }
                }
                else if (lastThumbnailRightEdge >= scrollBarRightEdge)
                {
                    isScrolling(true);
                    scrollbarList.animate({ left: left }, speed, null, function() { isScrolling(false); });
                }
            }
        };
        
        
        this.SelectNextPhoto = function() {
            var photoList = this.PhotoList();
            var flickrID = this.SelectedFlickrID();
            
            var selectedPhoto = this.GetPhotoInfoByID(flickrID);
            
            var selectedPhotoIndex = $.inArray(selectedPhoto, photoList);
            
            if (selectedPhotoIndex == photoList.length - 1)
            {
                selectedPhotoIndex = 0;
            }
            else
            {
                selectedPhotoIndex++;
            }
            
            this.SelectPhoto(photoList[selectedPhotoIndex].FlickrID);
        };
        
        
        this.SelectPreviousPhoto = function() {
            var photoList = this.PhotoList();
            var flickrID = this.SelectedFlickrID();
            
            var selectedPhoto = this.GetPhotoInfoByID(flickrID);
            
            var selectedPhotoIndex = $.inArray(selectedPhoto, photoList);
            
            if (selectedPhotoIndex == 0)
            {
                selectedPhotoIndex = photoList.length - 1;
            }
            else
            {
                selectedPhotoIndex--;
            }
            
            this.SelectPhoto(photoList[selectedPhotoIndex].FlickrID);
        };
        
        
        this.Pause = function() {
            if (changeInterval != null)
            {
                clearInterval(changeInterval);
                changeInterval = null;
            }
        };
        
        
        this.Play = function() {
            changeInterval = setInterval(function() {
                obj.SelectNextPhoto();
            }, this.SlideshowInterval());
        };
        
        
        this.SelectPhoto = function(flickrID) {
            var selectedPhoto = this.GetPhotoInfoByID(flickrID);
            var image = this.GetImageByID(flickrID);
            
            this.SelectedFlickrID(flickrID);
            
            $("#lblName").text(selectedPhoto.Name);
            $("#lblLocation").text(selectedPhoto.Location);
            $("#lblCaption").text(selectedPhoto.Caption);
            
            if (this.SelectedThumb() != null)
            {
                this.SelectedThumb().removeClass("selected");
            }
            
            
            if (image.complete)
            {
                var fullSizeImage = $("a#fullsizeImage");
                
                fullSizeImage.children("img").remove();
                fullSizeImage.append(image);
                fullSizeImage.attr("href", selectedPhoto["FlickrUrl"]);

				$(image).css({
                    display: "block",
                    position: "relative", 
                    top: (parseInt(fullSizeImage.css("height")) / 2) - (image.height / 2),
                    left: (parseInt(fullSizeImage.css("width")) / 2) - (image.width / 2) 
                });
            }
            else
            {
                var loadTimeout = 200;
            
                var interval = null;
                
                interval = setInterval(function() {
                    if (image.complete) 
                    { 
                        clearInterval(interval); 
                        
                        var fullSizeImage = $("a#fullsizeImage");
                        
                        fullSizeImage.children("img").remove();
                        fullSizeImage.append(image);
                        fullSizeImage.attr("href", selectedPhoto["FlickrUrl"]);

						$(image).css({
                			display: "block",
                			position: "relative", 
                			top: (parseInt(fullSizeImage.css("height")) / 2) - (image.height / 2),
                			left: (parseInt(fullSizeImage.css("width")) / 2) - (image.width / 2) 
            	        });
                    }
                }, loadTimeout);
            }
            
            
            var selectedThumb = $('a[name=' + flickrID + ']', scrollbarList);
            selectedThumb.addClass("selected");

            this.SelectedThumb(selectedThumb);
        };
        

        this.Initialize = function() {

            this.GetSlideshowPictureList({
                OnSuccess : function(result) {
					var photoList = result["Result"];
                    this.PhotoList(photoList);
                            
					scrollbarList = $("#scrollBarList");
                            
                    for (var index = 0; index < photoList.length; index++)
                    {
                        var photo = photoList[index];
                        scrollbarList.append("<li><a class='thumb loading' name='" + photo["FlickrID"] + "' title='" + photo["Caption"] + "' href='#'></a></li>");
                    }


                    $("a.thumb").click(function(event) {
                        event.preventDefault();
                                
                        obj.SelectPhoto($(this).attr("name"));
                        obj.Pause();
                                
                        $("#playButtonDiv").css("display", "inline");
                        $("#pauseButtonDiv").css("display", "none");
                    });
                            
                            
                    // Display the first image in full size view. 
                    if (photoList.length > 0)
                    {
                        // Pre-load all of the thumbnail images in the scroll bar. 
                        this.PreLoadThumbs(0);
                        this.PreLoadImages(0);
                                
                        this.SelectPhoto((photoList[0]).FlickrID);
                                
                        this.Play(); // Start the slideshow on load by default.
                    }
                }
			});
        }
        
        
        this.GetPhotoInfoByID = function(flickrID) {        
            var photoList = this.PhotoList();
            var photo = null;
            
            for (var index = 0; index < photoList.length; index++)
            {
                if ((photoList[index])["FlickrID"] === flickrID)
                {
                    photo = photoList[index];
                    break;
                }
            }
            
            return photo;
        };
        
        
        this.GetImageByID = function(flickrID) {
            var imagesList = this.PreLoadedImages();
            var image = null;
            
            for (var index = 0; index < imagesList.length; index++)
            {
                if ((imagesList[index]).name === flickrID)
                {
                    image = imagesList[index];
                    break;
                }
            }
            
            return image;
        };
        
        
        this.PreLoadThumbs = function(index) {
            if (index < this.PhotoList().length)
            {
                var thumb = new Image(this.ThumbWidth(), this.ThumbHeight());
                thumb.index = index;
                
                $(thumb).load(function(event) {
                    var photoIndex = this.index;
                    var thumbAnchor = $('a[name=' + obj.PhotoList()[photoIndex].FlickrID + ']', scrollbarList);
                    
                    thumbAnchor.removeClass("loading");
                    thumbAnchor.append($(this));
                    
                    obj.PreLoadThumbs(photoIndex + 1);
                });


				var photo = this.PhotoList()[index];
                
                thumb.src = photo.ThumbLocation;
                thumb.name = photo.FlickrID;
                
                var preLoadedThumbs = this.PreLoadedThumbs();
                preLoadedThumbs.push(thumb);
                
                this.PreLoadedThumbs(preLoadedThumbs);
            }
        };
        
        
        this.PreLoadImages = function(index) {
            if (index < this.PhotoList().length)
            {				
				var image = new Image();
                image.index = index;
                
                $(image).load(function(event) {
                    var photoIndex = this.index;
                    obj.PreLoadImages(photoIndex + 1);
					
					var imageWidth = obj.ImageWidth();
					var imageHeight = obj.ImageHeight();
					
					var aspectRatio = this.width / this.height;
					
					if (this.width > imageWidth && this.width > this.height)
					{
						// The width needs to be constrained.
						this.width = imageWidth;
						this.height = imageWidth / aspectRatio;
					}
					else if (this.height > imageHeight && this.height > this.width)
					{
						// The height needs to be constrained.
						this.width = aspectRatio * imageHeight;
						this.height = imageHeight;
					}
					else if ((this.width > imageWidth || this.height > imageHeight) && this.width === this.height)
					{
						if (imageWidth > imageHeight)
						{
							// Both the width and height need to be constrained to the desired height.
							this.width = imageHeight;
							this.height = imageHeight;
						}
						else
						{
							// Both the width and height need to be constrained to the desired width.
							this.width = imageWidth;
							this.height = imageWidth;
						}
					}
					
					this.style.display = "";
                });
                

				var photo = this.PhotoList()[index];

				image.style.display = "none";
                image.src = photo.ImageLocation;
                image.name = photo.FlickrID;
                
                var preLoadedImages = this.PreLoadedImages();
                preLoadedImages.push(image);
                
                this.PreLoadedImages(preLoadedImages);
            }
        };
        
        
        
		// Initial Load.
		/*this.ImageWidth(533);
		this.ImageHeight(430);
		this.ThumbWidth(70);
		this.ThumbHeight(60);*/
		
		this.ImageWidth($("a#fullsizeImage").width());
		this.ImageHeight($("a#fullsizeImage").height());

		this.Initialize();
    };
})(jQuery);
