﻿LangloWeb.SlideShowManager = function(galleryMgr) 
{
    this._prodGalleryMgr = galleryMgr;
    // Declare private variables and set to a known state
    this._imageIds = null;
    this._fadeInImage = null; 
    this._fadeOutImage = null;  
    this._curImage = null;
    this._selectedIndex = 0; 
    this._playing = false; 
    this._playTimerId = -1;
    this._fadeTimerId = -1;
    this._imgsDiv = null;
    this._photoPos = null;
    this._playPending = false;
    this._inTrans = false;
    this._fadeDelegate = null;
    this._playTimerDelegate = null;
    this._getTitleDelegate = null;
    this._getDescriptionDelegate = null;

    this._imgHeight = 310;
    this._slideInterval = 3000;
    this._fadeStep = 0.030; // delta opacity (goes from 0 to 1)
    this._fadeInterval = 33; // 33 ms -> 30 frames/sec.
}

LangloWeb.SlideShowManager.prototype = 
{
    handleNavBarMouseout : function() // NOT USED ANYMORE 
    {
        var navDiv = $get('pnlNav'); 
        photoHelper.setOpacity(navDiv, 0.5); 
    }, 
    
    handleNavBarMouseover : function() // NOT USED ANYMORE 
    {
        var navDiv = $get('pnlNav'); 
        photoHelper.setOpacity(navDiv, 0.75); 
    },
    
    handleFullImageLoaded : function() 
    {
        // Hide splash, show img
        $get('PopupSplashDiv').style.display = 'none';
        $get('BigImageDiv').style.display = '';
        $get('lbClose').style.display = '';
        var modalPopup = $find('BigImageBehavior');        
        if (modalPopup) 
            modalPopup._layout();
    },
    
    closeFullImage : function() 
    {
        var modalPopup = $find('BigImageBehavior');   
        if (modalPopup)
            modalPopup.hide();
        // Reset default visibility (hide img, show splash)
        $get('BigImageDiv').style.display = 'none';
        $get('lbClose').style.display = 'none';
        $get('PopupSplashDiv').style.display = '';
        if (this._playPending)
        {
            this._playPending = false;
            this.play();
        }
    },
  
    displayFullPageImage : function(imgId)
    {
        var tempDiv = $get('BigImageDiv'); 
        if (tempDiv) 
        {
            if (this._playing)
            {
                this.abortTransition();
                this.pause();
                this._playPending = true;
            }

            tempDiv.removeChild(tempDiv.firstChild);

            var img = document.createElement('img'); 
            img.id = 'Full' + imgId;

            var closeLink = $get('lbClose');
            var delegate = Function.createDelegate(this, this.closeFullImage);
            $addHandler(img, 'click', delegate); 
            $addHandler(closeLink, 'click', delegate); 

            var alreadyLoaded = false;
            var doOnLoaded = function(thisContext) 
                {
                    if (!alreadyLoaded)
                    {
                        alreadyLoaded = true;
                        thisContext.handleFullImageLoaded();
                    }
                };
            var doOnErrorOrAbort = function(thisContext)
                {
                    // TODO Display error msg
                    thisContext.closeFullImage();
                };
                
            // $common is from common.js in the Ajax Toolkit (it helps with browser comp. issues)
            var clientBounds = $common.getClientBounds();
            var clientWidth = clientBounds.width;
            var clientHeight = clientBounds.height;
                
            var src = photoHelper.getLoaderURL(imgId, clientHeight-25, clientWidth-20, 'Uniform'); 
            photoHelper.loadImage(this, img, src, doOnLoaded, doOnErrorOrAbort, doOnErrorOrAbort);

            tempDiv.appendChild(img); 
        }
    },

    gotoIndex : function(myIndex)
    {
        if (this._playing)
        {
            // Stop the timer now. It will be restarted at the end of the trans sequence
            this.clearPlayTimer();
        }
        switch (myIndex)
        {
            case -1: 
                if (this._selectedIndex > 0) 
                    this._selectedIndex--;
                else
                    this._selectedIndex = this._imageIds.length -1; 
                break;
            case 0: 
                this._selectedIndex = 0; 
                break;
            case 1:
                if (this._selectedIndex < this._imageIds.length - 1) 
                    this._selectedIndex++;
                else
                    this._selectedIndex = 0; 
                break;
            default: 
                this._selectedIndex = this._imageIds.length - 1;
                break;
        }
        this.startTransition();
    }, 
    
    handlePlayTimer : function()
    {
        if (this._playing)
            this.gotoIndex(+1); 
    }, 

    scheduleNextSlide : function()
    {
        this._playTimerId = setTimeout(this._playTimerDelegate, this._slideInterval);
    },
    
    clearPlayTimer : function()
    {
        if (this._playTimerId > -1)
        {  
            clearTimeout(this._playTimerId);
            this._playTimerId = -1;
        }
    }, 

    pause : function()
    {
        if (this._playing)
        {  
            this._playing = false;
            this.clearPlayTimer();
        }
    }, 
    
    play : function()
    {
        if (this._imageIds.length > 1 && !this._playing)
        {
            this._playing = true;
            //this.scheduleNextSlide(); <-- causes a wait before first slide
            this.gotoIndex(+1);
        }
    },

    /*        
    setPlayBtnImage : function(aURL)
    {
        var playBtn = $get('btnPlayPhoto'); 
        if (this.playBtn) 
            this.playBtn.style.backgroundImage = 'url(' + aURL + ')';
    },
    */
    
    togglePlay : function(obj) 
    {
        // TODO Move updating of btn.src to the play and pause methods
        if (this._playing) 
        {
            obj.src = 'Images/Aug07/play.jpg'; 
            //this.setPlayBtnImage('Images/Play.gif');
            this.pause();
        }
        else 
        {
            obj.src = 'Images/Aug07/stop.jpg'; 
            //this.setPlayBtnImage('Images/Stop.gif');
            this.play();
        }
        return false; 
    }, 
    
    first : function() { this.gotoIndex(0); return false; },
    prior : function() { this.gotoIndex(-1); return false; },
    next : function() { this.gotoIndex(+1); return false; },
    last : function() { this.gotoIndex(2); return false; },

    showFullPageImage : function() 
    {
        this.displayFullPageImage(this._imageIds[this._selectedIndex]); 
    }, 

    displayPhotoIndex : function()
    {
        if (this._photoPos != null)
            this._photoPos.innerHTML = (this._selectedIndex + 1) + ' av ' + this._imageIds.length; 
    },

    // Cleans up after a completed or aborted transition    
    endTransition : function()
    {
        if (this._inTrans)
        {
            if (this._fadeOutImage != null)
            {
                // Hide faded out image
                this._fadeOutImage.style.display = 'none';
                this._fadeOutImage.style.zIndex = 0;
                this._fadeOutImage = null;
            }
            // set new current image
            this._curImage = this._fadeInImage;
            this._fadeInImage = null;
            
            clearTimeout(this._fadeTimerId);
            this._fadeTimerId = -1;
            this._inTrans = false;
        }
    },
    
    doTransition : function() 
    {
        if (this._inTrans)
        {
            var fadeOutOpacity = 0;
            if (this._fadeOutImage != null)
                fadeOutOpacity = photoHelper.incOpacity(this._fadeOutImage, -this._fadeStep);
                
            var fadeInOpacity = 1;
            if (this._fadeInImage != null)
                fadeInOpacity = photoHelper.incOpacity(this._fadeInImage, +this._fadeStep);
        	
            if (fadeOutOpacity <= 0 && fadeInOpacity >= 0.99) 
            {
                // Trans successfully completed!
                this.displayPhotoIndex();
                if (this._playing)
                    this.scheduleNextSlide();
                this.endTransition();
            }
            else
	            this._fadeTimerId = setTimeout(this._fadeDelegate, this._fadeInterval);
	    }
    },

    handleGotDescription : function(searchResult) 
    {
        var descrElem = $get('slideShowDescription');
        if (typeof descrElem != 'undefined' && descrElem != null)
            if (searchResult.WasFound)
                descrElem.innerHTML = searchResult.Value != null ? searchResult.Value : "";
            else
                descrElem.innerHTML = '';
    }, 
    
    handleGotTitle : function(searchResult) 
    {
        var titleElem = $get('slideShowTitle'); 
        if (typeof titleElem != 'undefined' && titleElem != null)
            if (searchResult.WasFound)
                titleElem.innerHTML = searchResult.Value != null ? searchResult.Value : "";
            else
                titleElem.innerHTML = '';
    }, 

    displayImgMetadata : function(imgId)
    {
        // TODO Cache metadata?
        PhotoTagService.TryGetPhotoTitle(imgId, this._getTitleDelegate);
        PhotoTagService.TryGetPhotoDescription(imgId, this._getDescriptionDelegate);
    },
    
    loadMediumImage : function(imgId, displayNow)
    {  
        if (typeof imgId != 'undefined')
        {
            var img = document.createElement('img'); 
            img.id = 'Medium' + imgId;
            img.imageId = imgId;
		    img.style.display = displayNow ? 'inline' : 'none';
		    var opacity = displayNow ? 1 : 0;
            photoHelper.setOpacity(img, opacity);
            img.src = photoHelper.getLoaderURL(imgId, this._imgHeight); 
            this._imgsDiv.appendChild(img); 
            return img;
        }
        else
            return null;
    }, 

    abortTransition : function()
    {
        this.endTransition();
    },
    
    startTransition : function() 
    {
        if (this._inTrans)
            this.abortTransition();
            
        var myDiv = this._imgsDiv;
        var priorImage = this._curImage;
        var nextImage = null; 
        var targetId = this._imageIds[this._selectedIndex];
        var len = myDiv.childNodes.length;
        for (var i = 0; i < len; i++) 
        {
            var node = myDiv.childNodes[i];
            if (node.nodeName == 'IMG' && node.imageId == targetId)
            {
                nextImage = node;
                break;
            }
        }
        if (nextImage == null)
            nextImage = this.loadMediumImage(targetId, false);

        this._inTrans = true;
        this._fadeOutImage = priorImage;
        this._fadeInImage = nextImage;

        if (nextImage != null)
        {
            // Move to front, make visible (while still having 0 opacity)
            nextImage.style.zIndex = 2; 
		    nextImage.style.display = 'inline';

            // Load metadata (from server) while transitioning...
            this.displayImgMetadata(targetId);
            
            var doOnLoaded = function(thisContext) 
                { 
                    if (thisContext._inTrans)
                    {
                        thisContext.doTransition(); 
                    }
                };
            var doOnErrorOrAbort = function(thisContext)
                {
                    thisContext._inTrans = false;
                };
            photoHelper.handleImageLoad(this, nextImage, doOnLoaded, doOnErrorOrAbort, doOnErrorOrAbort);
        }
        else
            thisContext.doTransition(); 
    },
    
    // Loads imageId's into this._imageIds array and passes count as return value.
    loadImageIds : function() 
    {
        var counter = 0;
        this._imageIds = new Array();
        var myDiv = this._prodGalleryMgr.getThumbsElement();
        if (myDiv != null)
        {
            var len =  myDiv.childNodes.length;
            for (var i = 0; i < len; i++) 
            {
                var node = myDiv.childNodes[i];
                if (node.nodeName == 'IMG' && node.style.display != 'none')
                {
                    var imageId = node.imageId; 
                    if (typeof imageId == 'undefined') 
                        imageId = node.getAttribute('imageId')
                    if (typeof imageId != 'undefinded') 
                        this._imageIds[counter] = imageId;
                    counter++; 
                }
            }
        }
        return counter;
    },

    deactivate : function()
    {
        this.abortTransition();
        this.pause();
        this._playPending = false;
        this._photoPos = null;
        this._imgs = null;
        this._fadeDelegate = null;
        this._playTimerDelegate = null;
        this._getTitleDelegate = null;
        this._getDescriptionDelegate = null;
    },
    
    dispose : function()
    {
        this.deactivate();
        this._prodGalleryMgr = null;
    },
    
    activate : function(imageId)
    {
        // Initialize
        this._playing = false; 
        this._photoPos = $get('photoPos');
        
        // Use delegates to give the event handlers access to "this"
        this._fadeDelegate = Function.createDelegate(this, this.doTransition);
        this._playTimerDelegate = Function.createDelegate(this, this.handlePlayTimer);
        this._getTitleDelegate = Function.createDelegate(this, this.handleGotTitle);
        this._getDescriptionDelegate = Function.createDelegate(this, this.handleGotDescription);
        
        if (this.loadImageIds() > 0)
        {
            this._selectedIndex = Array.indexOf(this._imageIds, imageId.toString()); 
            // Test to see if imageId is in the array. If not set imageId to first image in array
            if (this._selectedIndex == -1) 
            {
                this._selectedIndex = 0; 
                imageId = this._imageIds[0]; 
            }
            // Display
            this._imgsDiv = $get('slideShowImages'); 
            this._imgsDiv.innerHTML = '';
            var img = this._curImage = this.loadMediumImage(imageId, true);
            this.displayImgMetadata(imageId);
            this.displayPhotoIndex();

            // By setting the height of the parent panel we ensure that divs below the image are
            // positioned correctly and that the outer frame is tall enough.
            var doOnLoaded = function(thisContext) 
                { 
                    var imgBounds = Sys.UI.DomElement.getBounds(img);
                    var panel = img.parentNode;
                    panel.style.height = imgBounds.height;
                };
            photoHelper.handleImageLoad(this, img, doOnLoaded);
        }
    }
}

// Register the class with the script manager. 
LangloWeb.SlideShowManager.registerClass('LangloWeb.SlideShowManager'); 
 
// The slideShowMgr is now a property of the LangloWeb.ProductGalleryManager class
// if (typeof document.getElementById != 'undefined')
//    slideShowMgr = new LangloWeb.SlideShowManager();

if (typeof(Sys) !== 'undefined')
    Sys.Application.notifyScriptLoaded();