﻿var currentRotationIndex = 0;
var rotationIntervalTimeoutId = null;
var currentVisibleFlipperItem = null;
var currentVisibleFlipperLink = null;
var rotationDataIds = null;
var rotationLinkIds = null;
var rotationDelay = null;

window['RunBillboardSwitching'] = true;

function LoadAutomaticBillboardChange(object, dataIds, linkIds, defaultDataId, defaultLinkId, delay)
{
    rotationDataIds = dataIds;
    rotationLinkIds = linkIds;
    
    rotationDelay = delay;
    
    clearInterval(rotationIntervalTimeoutId);
    
    rotationIntervalTimeoutId = setInterval(function() { RotateBillboard(defaultDataId, defaultLinkId); }, rotationDelay);
}

function RotateBillboard(defaultDataId, defaultLinkId)
{
    if(window['RunBillboardSwitching'] == null || window['RunBillboardSwitching'])
    {
        if(rotationDataIds != null && rotationLinkIds != null)
        {
            if(currentRotationIndex < rotationDataIds.length - 1)
            {
                currentRotationIndex++;
            } 
            else 
            {
                currentRotationIndex = 0;
            }
               
            var divId = rotationDataIds[currentRotationIndex];
            var linkId = rotationLinkIds[currentRotationIndex];
               
            DisplayFlipperData(divId, linkId, defaultDataId, defaultLinkId);
        }
    }
}

function DisplayFlipperData(dataID, linkID, defaultDataID, defaultLinkID)
{
    var currentItem = currentVisibleFlipperItem;
    var currentLink = currentVisibleFlipperLink;
    var newItem = $(dataID);
    var newLink = $(linkID);
    
    if(currentItem == null)
    {
        currentItem = $(defaultDataID);
    }
    
    if(currentLink == null)
    {
        currentLink = $(defaultLinkID);
    }   
    
    if(currentItem != null && newItem != null && currentLink != null && newLink != null)
    {
        if(linkID != currentLink.id)
        {
            currentItem.fade({duration: 0.3 });
            newItem.appear({duration: 0.3, queue: 'end' });
            
            currentLink.className = '';
            newLink.className = 'Selected';
            
            currentVisibleFlipperItem = newItem;
            currentVisibleFlipperLink = newLink;
            
            clearInterval(rotationIntervalTimeoutId);
            
            rotationIntervalTimeoutId = setInterval(function() { RotateBillboard(defaultDataID, defaultLinkID); }, rotationDelay);
        }
    }
}