﻿function promoItemBAHome_flashDone() {
    for (var i = 0; i < globalFlashPlayers.length; i++) {
        globalFlashPlayers[i].rotate(true);
    }
}

globalFlashPlayers = [];

Volvo.CWP.FlashImageRotator = function(id, autorotate) {
    this.container = document.getElementById(id);
    this.isrotating = autorotate;
    this.rotatorDelegate = Volvo.CWP.createDelegate(this, this.rotate);
    this.init();
    if (this.isrotating) {
        window.setTimeout(this.rotatorDelegate, 4000);
    }
    globalFlashPlayers.push(this);
};

Volvo.CWP.FlashImageRotator.prototype.init = function() {
    this.displays = $(this.container).find('.display').toArray(); 
    this.thumbnails = this.container.getElementsByTagName('li');
    var clickDelegate = Volvo.CWP.createDelegate(this, this.handleItemClick);
    for (var i = 0; i < this.thumbnails.length; i++) {
        this.thumbnails[i].getElementsByTagName('a')[0].onclick = clickDelegate;
    }
    this.activeIndex = 0;
};

Volvo.CWP.FlashImageRotator.prototype.rotate = function(force) {
    if (!this.isrotating) {
        return;
    }
    if (!force) {
        if (this.itemIsFlash(this.activeIndex)) {
            return;
        }
    }
    var nextIndex = (this.activeIndex >= this.displays.length - 1) ? 0 : this.activeIndex + 1;
    this.setActiveIndex(nextIndex);
    window.setTimeout(this.rotatorDelegate, 4000);
};

Volvo.CWP.FlashImageRotator.prototype.itemIsFlash = function(index) {
    return (this.displays[index].innerHTML.toLowerCase().indexOf('<object') > -1
        || this.displays[index].innerHTML.toLowerCase().indexOf('<embed') > -1)
};

Volvo.CWP.FlashImageRotator.prototype.handleItemClick = function(e) {
    var sender = (e && e.target) || (window.event && window.event.srcElement);
    var selectedIndex = -1;
    for (var i = 0; i < this.thumbnails.length; i++) {
        if (Volvo.CWP.containsElement(this.thumbnails[i], sender)) {
            selectedIndex = i;
            break;
        }
    }
    if (selectedIndex > -1) {
        this.setActiveIndex(selectedIndex);
    }
    this.isrotating = false;
    return false;
};

Volvo.CWP.FlashImageRotator.prototype.setActiveIndex = function(index) {
    this.thumbnails[this.activeIndex].className = '';
    this.displays[this.activeIndex].style.display = 'none';
    this.reloadItem(index);
    this.thumbnails[index].className = 'selected';
    this.displays[index].style.display = 'block';
    this.activeIndex = index;
};

Volvo.CWP.FlashImageRotator.prototype.reloadItem = function(index) {
    var itemMarkup = this.displays[index].innerHTML;
    this.displays[index].innerHTML = '';
    this.displays[index].innerHTML = itemMarkup;
    var scripts = this.displays[index].getElementsByTagName('script');
    for (var i = 0; i < scripts.length; i++) {
        eval(scripts[i].innerHTML);
    }
};