﻿var _rotateSpeed = 2500;    //milliseconds
var _animationSpeed = 2000;   //milliseconds
var _urlPrefix = "picScaler.ashx?width=800&imgWidth=800&imgHeight=482&image=";  //Used to navigate image url to server script or specialized path
    
var _images;        //Image Array
var _background;    //Div or Container holding image
var _eImage;        //Image Element
var _activeIndex;

var _rotationTimer = null;  //Tracks time between image switches
var _animationTimer = null; //Tracks time taken to animate fade
var _rotationComplete;      //Event

var _rotationToggle = 0;		//used to identify which layer (eImage = 0 or bakcground = 1) to use when loading next image
//var _currentOpacity = 1;
//var _animationStep = .1;    //Rate that the fade occurs.  This step occurs every time the _animationSpeed is reached.

var _preCache;
var _preCacheCount = 0;
    
//Initialize Images and elements to Rotate
function initRotatePics(imageArray, backgroundPanel, imageElement)
{
    _images = imageArray;
    _background = $('#'+backgroundPanel.id);  //Div or Container holding image
    _eImage = $('#'+imageElement.id); //Image Element
    
    _activeIndex = 0;   //Start at zero
    _eImage.attr("src",_urlPrefix + _images[_activeIndex]);	//Load First Image into Image Element
    
    cacheImages();	//Cache Other Images in Array
}

//Precaches images
function cacheImages()
{
    _preCache = new Array(_images.length);
    
    for(var i = 0;i<_images.length;i++)
    {
        var imageUrl = _urlPrefix + _images[i];
        _preCache[i] = new Image();
        _preCache[i].src = imageUrl;
        _preCache[i].onload = preCache_load;    
    }
}
//Tracks the number of images that are pre-cached
function preCache_load()
{
    _preCacheCount++;
	
	if(_preCacheCount >= _images.length)
	{
		_startRotatePics();
	}
}
        
//Start Rotation - Depreciated
function startRotatePics(){}

//Initiate the Rotation Process
function _startRotatePics()
{
    _rotationComplete = null;   //Clear rotation Complete
    if(this._rotationTimer != null)
        return; //Timer running -- already started    
        
    if( (_preCacheCount >= _images.length))
    {
        _rotationTimer = setTimeout("rotateImage()", _rotateSpeed); 
    }
    else
    {
        setTimeout(_startRotatePics,_rotateSpeed/3); //Keep checking -- still caching!
    }
}

//function stopRotatePics()
//{
//    clearInterval(_rotationTimer);
//    clearInterval(_animationTimer);
//    switch(_rotationToggle)
//    {
//        case 0:
//            _currentOpacity = 1;
//            setOpacity();
//            break;
//        case 1:
//            _currentOpacity = 0;
//            setOpacity();
//            break;
//    }
//}

function forceRotatePic(imageUrl)
{
    clearTimeout(_rotationTimer);
    clearInterval(_animationTimer);

    
    switch(_rotationToggle)
    {
        case 1:
//            _currentOpacity = 0;
//            setOpacity();
            _eImage.attr("src",_urlPrefix + imageUrl);
            _rotationToggle = (_rotationToggle + 1) % 2;
            loadImage(false);
            break;
        case 0:
//            _currentOpacity = 1;
//            setOpacity();
            _background.css("background","#000 url(" + _urlPrefix + imageUrl +") no-repeat center center"); 
            _rotationToggle = (_rotationToggle + 1) % 2;
            loadImage(false);
            break;
    }
}

//Execute Swapping of Image
function rotateImage() // = function()
{
    //Get New Index
    var newIndex = _activeIndex + 1;
    
    //Check New Index - stay within bounds
    if(newIndex > _images.length - 1) {newIndex = 0;}
            
    //Load Image File into Location
    //window.status = ("Go Image " + newIndex);
    _activeIndex = newIndex;
    _rotationToggle = (_rotationToggle + 1) % 2;	//Determines how to toggle layers (image and background) to perform proper fade
    loadImage(true);
}

//Determine loading location based on item Index
//Clear rotationTimer - stops rotation count while animation is executing
//All even number indexes are loaded in the Image Element, odd number indexes are loaded on background panel
//Once image is loaded, it will initiate the "fade" method
function loadImage(usePreCache)
{
    //Clear Timer
    clearTimeout(_rotationTimer); _rotationTimer = null;
    var loadDelay = 150;	//Needed to give browser time to load image into element.  Otherwise you see the old picture for about a half a second flash.
        
    //_eImage.css({opacity: 0.5});
    switch(_rotationToggle)
    {
        //Load Image in eImage
        case 0:
            if(usePreCache){_eImage.attr("src",_preCache[_activeIndex].src);}
            _eImage.css({opacity: 0.0})
                .animate({opacity: 1.0}, _animationSpeed, 
                            function() {
                                if(usePreCache)
                                    _rotationTimer = setTimeout(rotateImage,_rotateSpeed);
                            });
            break;
        
        //Load Image in background
        case 1:
        if(usePreCache){_background.css("background","#000 url(" +_preCache[_activeIndex].src +") no-repeat center center"); }
        _eImage.css({opacity: 1.0})
            .animate({opacity: 0.0}, _animationSpeed, 
                            function() {
                                if(usePreCache)
                                    _rotationTimer = setTimeout(rotateImage,_rotateSpeed);
                            });

        break;
    }
}

//Handles fade animation process
//Keep track of opacity status and stop fade while new opactiy is 100%
//Restarts rotationTimer once fade is complete
//function startFade(decreaseOpacity)
//{
//    window.status = ("Current Opacity: " + _currentOpacity);
//    
//    //Check Opacity
//    if(
//        (decreaseOpacity && _currentOpacity > 0)
//        || (!decreaseOpacity && _currentOpacity < 1))
//    {
//        //Take the animation step and make it negative if we are decreasing opacity. Positive if we are increasing
//	    _currentOpacity = _currentOpacity + _animationStep * (decreaseOpacity?-1:1);
//	    if(_currentOpacity < 0){_currentOpacity = 0;}
//	    if(_currentOpacity > 1){_currentOpacity = 1;}
//        setOpacity()
//    } 
//    else
//    {
//        //Animation complete -- stop animation timer and start rotation again!
//        clearInterval(_animationTimer);
//        _rotationTimer = setInterval("rotateImage()", _rotateSpeed);
//        
//        //Event Handler for Other Scripts or Start Rotation Again!
//        if(_rotationComplete)
//        {
//            _rotationComplete();
//        }
//        
//   }
//}

//function setOpacity()
//{
//    if(document.all)
//    {
//	    _eImage.style.filter = "alpha(opacity = " + _currentOpacity * 100 + ")";
//    }
//    else
//    {
//	    _eImage.style.opacity = _currentOpacity;
//    }
//}

////Retrieve current element styles
//function getStyle(el,styleProp)
//{
//    var x;
//    if(typeof el == "string")
//    {
//        x = document.getElementById(el);
//    }
//    else
//    {
//        x = el;
//    }
//	
//	var y;
//    if (x.currentStyle)
//	    y = x.currentStyle[styleProp];
//    else if (window.getComputedStyle)
//	    y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
//    return y;
//}
