
// VIDEO HOMEPAGE /////////////////////////////////////////////////////////////////////////////////////////////////////////////
var playerObj = null;
var cookieHomeVideo = 'spothome';
var cookieHomeVideoDuration = 365;

function pComplete(obj) {
    if ($('homeVideo') && $('spotVideo')) {
        if (obj.newstate == "COMPLETED") {
            // Scrivo il cookie
            Cookie.write(cookieHomeVideo, '1', { duration: cookieHomeVideoDuration, path: '/' });
            // Nascondo la finestra
            playerObj.sendEvent("PLAY", false);
            var hideVideo = function () {
                $('homeVideo').tween('opacity', 0);
            }
            hideVideo.delay('300');
        }
    }
}

function playerReady(obj) {
    playerObj = document.getElementById(obj['id']);
    if (playerObj) {
        playerObj.addModelListener('STATE', 'pComplete');
    }
}

//function skipIntro() {
//    // Scrivo il cookie
//    Cookie.write(cookieHomeVideo, '1', { duration: 0, path: '/' });
//    playerObj.sendEvent("PLAY", false);
//    $('homeVideo').tween('opacity', 0);
//}

window.addEvent('domready', function () {
    // Identifico se il video è presente
    if ($('homeVideo') && $('spotVideo')) {
        $('homeVideo').set('tween', {
            duration: 800,
            onComplete: function () {
                $('spotVideo').destroy();
                $('homeVideo').setStyle('display', 'none');
            }
        })
    }
});


// GESTIONE SLIDE HOMEPAGE ////////////////////////////////////////////////////////////////////////////////////////////////////
var Slide = new Class({

    Implements: Options,

    options: {
        container: 'gallery',   /* Contenitore immagini */
        delay: 5000,            /* Durata attesa prossima immagine */
        duration: 1500          /* Durata transizione */
    },

    initialize: function (element, options) {
        this.element = this.subject = $A(element);
        this.setOptions(options);

        this.options.container = $(this.options.container);

        this.period = null;

        this.images = null;
        this.currentImage = 0;

        this.preloadSlide();
    },

    showImage: function (index) {
        if (index >= 0 && index < this.images.length) {
            // Stop slideshow
            $clear(this.period);
            // Se immaggine attuale != da index allora la mostro altriemnti è già li ;)
            if (this.currentImage != index) {
                this.images[this.currentImage].tween('opacity', 0);
                this.currentImage = index;
                this.images[this.currentImage].tween('opacity', 1);
            }
        }
    },

    changeImage: function () {
        this.images[this.currentImage].tween('opacity', 0);
        this.currentImage = (this.currentImage + 1) % this.images.length;
        this.images[this.currentImage].tween('opacity', 1);
    },

    runSlideshow: function () {

        this.images = this.options.container.getChildren('img');
        this.images.set('tween', { duration: this.options.duration });

        // Ciclo la gallery
        this.period = this.changeImage.periodical(this.options.delay, this);
    },

    preloadOthers: function () {

        // La prima è già caricata
        this.element = $A(this.element.slice(1, this.element.length));

        var myClass = this;

        var myImgs = new Asset.images(this.element, {
            onComplete: function () {
                myImgs.setStyles({ 'opacity': 0 });
                myImgs.inject(myClass.options.container);
                myClass.runSlideshow.run([], myClass);
            }
        });

    },

    preloadSlide: function () {

        var myClass = this;

        // Preload della prima poi tutte le altre
        var myBase = new Asset.image(this.element[0], {
            onload: function () {
                myBase.inject(myClass.options.container);
                myClass.preloadOthers.run([], myClass);
            }
        });

    }

});




// Parametri cookie
//var cookieName = 'layoutPos';
//var cookieDuration = 365; // days

// Percorso immagini per il tree menu
var subImgOpen = '/Master/casserurali2010/images/list_open.png';
var subImgClose = '/Master/casserurali2010/images/list_close.png';

// Dock menu
var myDock = null;
var mySlide = null;

window.addEvent('load', function () {

    // Gestione Dock Menu ////////////////////////////////////////////////////////////////////////////////////////////////////
    myDock = new Dock('dock', { elCaption: 'dockTitle', classCaption: 'specialTitle' });

    // Gestione del primo menu dinamico //////////////////////////////////////////////////////////////////////////////////////


});

var tabOne = null;
var tabTwo = null;
var tabNews = null;
var tabInbank = null;
var tabsContent = null;

//var layoutPos = null;

var closeTabsTimer = null;
var closeTabsTime = 10000;

function closeTabs() {
    tabOne.className = 'tabsNewsOff';
    tabTwo.className = 'tabsInbackOff';
    //layoutPos.set('posTabLeft', 0);
    tabOne.set('status', 'close');
    tabTwo.set('status', 'close');
    tabInbank.setStyle('display', 'none');
    tabNews.setStyle('display', 'none');
    tabsContent.tween('height', 0);

    //closeTabsTimer = setTimeout('closeTabs()', closeTabsTime);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

window.addEvent('domready', function () {

    /*
    //  inizio carousel news
    */
    var currentNews = 0;
    var onHover = false;

    var news = $$('.newsboxBlock');

    news.set('tween', {
        'duration': 1000,
        'onComplete': function (el) {
            el.inject(el.getParent(), 'bottom');
            el.setStyle('height', el.retrieve('initheight'));
        }
    });

    news.each(function (el) {
        el.store('initheight', el.getStyle('height').toInt());
        el.addEvent('mouseenter', function () {
            onHover = true;
        }).addEvent('mouseleave', function () {
            onHover = false;
        });
    });

    var changeNews = function () {
        if (onHover) {
            return;
        }
        news[currentNews].tween('height', 0);
        currentNews = (currentNews + 1) % news.length;
    }

    if (news.length > 0) {
        changeNews.periodical(5000);
    }

    /*
    //  fine carousel news
    */

    var listVoice = $$('.listVoice');
    var initListHeight = 27;
    if (!fPage) {
        listVoice.each(function (el) {
            el.set('tween', {
                duration: 500,
                onComplete: function () { }
            });

            var childs = el.getChildren('div');
            childs[0].addEvent('click', function () {
                listVoice.tween('height', initListHeight);
                if (childs[1].getChildren().length > 0) {
                    if (el.getStyle('height').toInt() <= initListHeight) {
                        el.tween('height', initListHeight + childs[1].getSize().y);
                    }
                }
            });
        });
    }

    // Apro il cookie
    //layoutPos = new Hash.Cookie(cookieName, {autoSave: true, duration: cookieDuration, path: '/' });
    //layoutPos.load();

    // Gestione tabs inbank, news /////////////////////////////////////////////////////////////////////////////////////////////////////////
    tabOne = $('tabOne');
    tabTwo = $('tabTwo');
    tabNews = $('tabNews');
    tabInbank = $('tabInbank');
    tabsContent = $('tabsContent');

    // Funzione per l'autochiusura del box
    if (!fPage) {
        closeTabsTimer = setTimeout('closeTabs()', closeTabsTime);
    }

    //var posTabLeft = layoutPos.get('posTabLeft');

    tabOne.set('status', 'close');
    tabTwo.set('status', 'close');

    if (fPage) { tabOne.set('status', 'open'); }

    if (!fPage) {
        tabsContent.set('defaultHeight', tabsContent.getStyle('height').toInt());
        tabsContent.set('tween', { duration: 200 });
        $$('.tabsBox').addEvent('mouseenter', function () { clearTimeout(closeTabsTimer); });
        $$('.tabsBox').addEvent('mouseleave', function () { closeTabsTimer = setTimeout('closeTabs()', closeTabsTime); });
    }

    // Se è null, quindi prima volta di defautl apro la seconda tab (news)
    //if(posTabLeft == null) { posTabLeft = 2; }

    // Se non sono nella prima pagina allora chiudo le tab
    if (!fPage) { closeTabs(); }

    tabOne.addEvent('click', function () {
        //        if (tabOne.get('status') == 'open') {
        if (tabOne.get('status') == 'open' && !fPage) {
            tabOne.className = 'tabOff';
            //layoutPos.set('posTabLeft', 0);
            tabOne.set('status', 'close');
            tabsContent.tween('height', 0);
            tabInbank.setStyle('display', 'none');
            tabNews.setStyle('display', 'none');
        }
        else {
            if ($('tabsContent').getStyle('height').toInt() <= 0 && !fPage) {
                tabsContent.tween('height', tabsContent.get('defaultHeight'));
            }
            tabOne.className = 'tabOn';
            tabTwo.className = 'tabOff';
            //layoutPos.set('posTabLeft', 1);
            tabInbank.setStyle('display', 'none');
            tabNews.setStyle('display', 'block');
            tabOne.set('status', 'open');
            tabTwo.set('status', 'close');
        }
    });

    tabTwo.addEvent('click', function () {
        //        if (tabTwo.get('status') == 'open') {
        if (tabTwo.get('status') == 'open' && !fPage) {
            tabTwo.className = 'tabOff';
            //layoutPos.set('posTabLeft', 0);
            tabTwo.set('status', 'close');
            tabsContent.tween('height', 0);
            tabInbank.setStyle('display', 'none');
            tabNews.setStyle('display', 'none');
        }
        else {
            if ($('tabsContent').getStyle('height').toInt() <= 0) {
                tabsContent.tween('height', tabsContent.get('defaultHeight'));
            }
            tabOne.className = 'tabOff';
            tabTwo.className = 'tabOn';
            tabInbank.setStyle('display', 'block');
            tabNews.setStyle('display', 'none');
            //layoutPos.set('posTabLeft', 2);
            tabOne.set('status', 'close');
            tabTwo.set('status', 'open');
        }
    });

    // Gestione sfondi tab con preload

    var s = [];
    s[0] = '/Master/casserurali2010/images/1sistema.jpg';
    s[1] = '/Master/casserurali2010/images/2banche.jpg';
    s[2] = '/Master/casserurali2010/images/3unite.jpg';
    s[3] = '/Master/casserurali2010/images/4comunita.jpg';


    if ($('tabs_imgs')) {
        // Gestione slide homepage
        mySlide = new Slide(s, { container: 'tabs_imgs' });
    }
    else {
        var myImgs = new Asset.images(s, {
            onComplete: function () {
                if ($('innertab0')) { $('innertab0').setStyle('background-image', 'url("' + myImgs[0].get('src') + '")'); }
                if ($('innertab1')) { $('innertab1').setStyle('background-image', 'url("' + myImgs[1].get('src') + '")'); }
                if ($('innertab2')) { $('innertab2').setStyle('background-image', 'url("' + myImgs[2].get('src') + '")'); }
                if ($('innertab3')) { $('innertab3').setStyle('background-image', 'url("' + myImgs[3].get('src') + '")'); }
            }
        });
    }

    // Gestione tabs nelle pagine /////////////////////////////////////////////////////////////////////////////////////////////////////////

    var innerButtons = $$('.btnInnerOff', '.btnInnerOffBlue');
    var innerContent = $$('.containerTabsInternoText');

    if (innerButtons.length > 0 && innerContent.length > 0) {
        var openedIndex = 0;    // Index aperta in questo momento
        var onFlide = 0;        // Semaforo flide in corso

        // Init slidingDiv
        var slidingDiv = $('slidingDiv');
        slidingDiv.setStyle('height', 0);

        // Init container
        var containerTabs = $('containerTabsInternoBig');
        containerTabs.setStyle('display', 'block');
        var marginTop = Number(-1 * containerTabs.getSize().y);
        containerTabs.setStyles({ 'opacity': 0, 'marginTop': marginTop });
        containerTabs.set('status', 'close');

        innerButtons.each(function (el, index) {
            el.addEvent('click', function () {
                if (containerTabs.get('status') == 'close') {
                    // Apertura della tab
                    slidingDiv.setStyle('height', 342);

                    /* BEGIN FLIDE IN */
                    innerContent[index].setStyle('display', 'block');
                    containerTabs.set('morph', { duration: 600, onComplete: function () { } });
                    containerTabs.morph({ 'opacity': 0.95, 'marginTop': 1 });
                    containerTabs.set('status', 'open');
                    /* END FLIDE IN */

                    innerButtons.each(function (iel) { iel.className = 'btnInnerOffBlue'; });
                    el.className = 'btnInnerOn';
                }
                else {
                    if (index == openedIndex) {
                        // Chiusura della tab

                        /* BEGIN FLIDE OUT */
                        containerTabs.set('morph', {
                            duration: 600,
                            onComplete: function () {
                                // Nascondo la tab aperta
                                innerContent.setStyle('display', 'none');
                                slidingDiv.setStyle('height', 0);
                                innerButtons.each(function (iel) { iel.className = 'btnInnerOff'; });
                            }
                        });
                        containerTabs.morph({ 'opacity': 0, 'marginTop': marginTop });
                        containerTabs.set('status', 'close');
                        /* END FLIDE OUT */
                    }
                    else {
                        // Chiusura della tab e apertura di un'altra

                        /* BEGIN FLIDE OUT */
                        containerTabs.set('morph', {
                            duration: 600,
                            onComplete: function () {
                                // Nascondo le tab aperte
                                innerContent.setStyle('display', 'none');
                                innerContent[index].setStyle('display', 'block');
                                /* BEGIN FLIDE IN */
                                containerTabs.set('morph', { duration: 600, onComplete: function () { } });
                                containerTabs.morph({ 'opacity': 0.95, 'marginTop': 1 });
                                containerTabs.set('status', 'open');
                                /* END FLIDE IN */
                            }
                        });
                        containerTabs.morph({ 'opacity': 0, 'marginTop': marginTop });
                        containerTabs.set('status', 'close');
                        /* END FLIDE OUT */

                        innerButtons.each(function (iel) { iel.className = 'btnInnerOffBlue'; });
                        el.className = 'btnInnerOn';
                    }
                }

                // Segnalo l'index aperta in questo momento
                openedIndex = index;
            });
        });
    }

    // Gestione tabs nella homepage /////////////////////////////////////////////////////////////////////////////////////////////////////////

    var tabButtons = $$('.btnTabOff');
    var tabContent = $$('.containerTabsText');

    if (tabButtons.length > 0 && tabContent.length > 0) {
        var activeTab = 0;  // Default 0
        var onFade = 0;     // Semaforo per fade

        // Nascondo di default tutte le tab e mostro la prima
        tabContent.setStyle('opacity', 0);
        tabContent.setStyle('display', 'block');
        tabContent[0].set('tween', { duration: 200 });
        tabContent[0].tween('opacity', 1);

        // Setto lo stile attivo sul primo bottone
        tabButtons[0].className = 'btnTabOn';

        tabButtons.each(function (el, index) {
            el.addEvent('click', function () {
                // Semaforo effetto fade
                if (onFade == 1) { return; }
                onFade = 1;

                // Nascondo la tab aperta
                tabContent[activeTab].set('tween', { duration: 500 });
                tabContent[activeTab].tween('opacity', 0);

                // Mostro la giusta tab
                tabContent[index].set('tween', {
                    duration: 500,
                    onComplete: function () { activeTab = index; onFade = 0; }
                });
                tabContent[index].tween('opacity', 1);

                // Metto tutti quelli diversi dal corrente ad Off
                tabButtons.each(function (iel) { iel.className = 'btnTabOff'; });
                tabButtons[index].className = 'btnTabOn';
            });
        });
    } // END controllo presenza button e tabs

    // Chiusura del DOMREADY
});

var loghiCasse = new Array(); // Init in default di cr
var imagesAlt = new Array(); // Lista alt loghi per ricerca

var imagesLoghi;

var numImages = 0;
var currLogo = 0;

var sizecontainer = 52;
var dimlogo = 72;
var margintop = 20;
var searchTimer;
var onCassaScroll = 0;


function handleLoghi() {
    numImages = loghiCasse.length;
    if (numImages > 0) {
        if ($('listLoghi')) {
            var preLoghi = new Array();
            for (i = 0; i < numImages; i++) {
                preLoghi[i] = loghiCasse[i][2];
            }
            imagesLoghi = new Asset.images(preLoghi, {
                onComplete: function () {
                    // BEGIN: Complete preload loghi

                    // Per ogni imamgine creo un div che la contenga e lo inserisco nel box dei loghi
                    imagesLoghi.each(function (img, index) {
                        var div = new Element('div', {
                            'class': 'wheelcasse'
                        });
                        var link = new Element('a', {
                            'href': loghiCasse[index][0],
                            'title': loghiCasse[index][1],
                            'events': {
                                'click': function () {
                                    window.open(loghiCasse[index][0]);
                                    return false;
                                }
                            }
                        });

                        img.className = 'imgwheel';
                        img.alt = loghiCasse[index][1];
                        imagesAlt[index] = loghiCasse[index][1];
                        img.inject(link);
                        link.inject(div);
                        div.inject('listLoghi');
                    });

                    $('listLoghi').setStyle('display', 'block');

                    // Fisso le dimensioni per explorer 6 e la trasparenza
                    if (ie6) { imagesLoghi.setStyles({ 'width': 160, 'height': 39 }); }

                    // Seleziona la prima cr
                    if (indexFirstCassa >= 0 && indexFirstCassa < numImages) {
                        var imgheight = imagesLoghi[indexFirstCassa].getStyle('height').toInt();
                        var offset = ((sizecontainer - imgheight) / 2) + 1;
                        var myScroll = new Fx.Scroll('listLoghi', { duration: 0, offset: { x: 0, y: -offset} });
                        myScroll.start(0, dimlogo * Number(indexFirstCassa) + margintop);
                        currLogo = Number(indexFirstCassa);
                    }

                    // END: Complete preload loghi
                }
            });
        }
    }
}

function searchCassa(sender) {
    var searchString = sender.value;
    searchTimer = $clear(searchTimer);
    searchTimer = goToCassa.delay(200, searchString);
}

var goToCassa = function () {
    var str = this;
    var i = 0;
    var found = 0;
    if (str.length >= 3) {
        while (i < numImages && found == 0) {
            if (imagesAlt[i].toLowerCase().indexOf(str) >= 0) {
                found = 1;
                scrollLogoTo(i);
            }
            i++;
        }
    }
}

function scrollLogo(v) {
    var nextLogo = Number(currLogo) + v;
    if (nextLogo >= numImages) { nextLogo = 0; }
    if (nextLogo < 0) { nextLogo = numImages - 1; }
    scrollLogoTo(nextLogo);
}

// scrolla al logo selezionato
function scrollLogoTo(pos) {
    if (onCassaScroll == 1)
        return;
    onCassaScroll = 1;
    var imgheight = imagesLoghi[pos].getStyle('height').toInt();
    var offset = ((sizecontainer - imgheight) / 2) + 1;
    var myScroll = new Fx.Scroll('listLoghi', {
        duration: 300,
        onComplete: function () {
            currLogo = pos;
            onCassaScroll = 0;
        },
        offset: { x: 0, y: -offset }
    });
    myScroll.start(0, dimlogo * pos + margintop);
}
