// on finish flash loader
//var introOptions = { xmlPath:"/html/xml/intro.xml", animation_path:"/html/flash/intro/" };
var panelImageDefault,panelNoFlash, panelImageBlank, panelImages, introFinished;

//set initial state
introFinished = false;

//on mini hover
panelImageDefault = "/html/images/home/bg/intro_bg.jpg";
panelNoFlash = "/html/images/home/bg/Homepage-stage0.jpg";
panelImageBlank = "/html/images/home/bg/intro_bg.jpg";
panelImages = [ ""
    ,"/html/images/home/bg/panel-patient.jpg"
    ,"/html/images/home/bg/panel-benefit.jpg"
    ,"/html/images/home/bg/panel-tube.jpg"
];

function preloadImages() {
    var d = document;
    if (d.images) {
        if (!d.p) d.p = new Array();
        var i,j = d.p.length, a = preloadImages.arguments;
        for (i=0; i<a.length; i++) {
            if (a[i].indexOf("#")!=0) {
                d.p[j] = new Image;
                d.p[j++].src = a[i];
            }
        }
    }
}


function showPanel (miniNo) {
    //highlight button
    $$('.mini').each(function(mini) { mini.removeClassName('on'); });

    $('mini'+miniNo).addClassName('on');

    // switch introbg
    $('containBg').style.backgroundImage = 'url(' + panelImages[miniNo] + ')';

    // remove intro
    if ($('intro')) {
        $('intro').style.display = 'none';
    }

    // remove panels
    $$('.panel').each( function(panel){ panel.display = 'none'; });

    $('panel'+miniNo).style.display = 'block';
}

function hidePanel (miniNo) {
    //unhighlight button
    $('mini'+miniNo).removeClassName('on');
    // switch main bg image
    var bgImg = (introFinished) ? panelImageDefault : panelNoFlash;
    $('containBg').style.backgroundImage = 'url(' + bgImg + ')';

    // show intro
    if ($('intro')) {
        $('intro').style.display='block';
    }

    // remove panels
    $('panel' + miniNo).hide();
}

function miniHoverInitial() {
    showPanel(this.id.split('mini')[1]); // why not use substr?
}

function miniHoverOutInitial() {
    hidePanel(this.id.split('mini')[1]); // why not use substr?
}

function postIntro() {
    $('miniWrapper').style.display = 'block';
    $('accordion').style.display = 'block';

    introFinished = true;

    //add a cookie to prevent future viewing for 28 days
    var date = new Date();
    var d28  = 28*24*60*60*1000;
    date.setTime( date.getTime() + d28 );
    var expires = '; expires=' + date.toGMTString();
    document.cookie = 'skipIntro=true' + expires;

    // show introbg
    $('containBg').style.backgroundImage = 'url(' + panelImageDefault + ')';

    $$('.mini').each(function (mini, index) {
        mini.addClassName('up');
        mini.observe('mouseover', miniHoverInitial);
        mini.observe('mouseout', miniHoverOutInitial);
        var effectOption = { delay: index * 0.2 };
        Effect.BlindDown(mini.getElementsByTagName('a')[0], effectOption);
    });

    // if an accordion is not already activated, open the top one
    var accordionDivs = $$('#accordion div h3');
    var accordionActive = false;

    accordionDivs.each(function(accordion) {
        if ($(accordion).hasClassName('on')) {
            accordionActive = true;
        }
    });

    if (!accordionActive) {
        accordionDivs[0].addClassName('on');
        Effect.BlindDown(accordionDivs[0].parentNode.getElementsByTagName('div')[0], {delay:0.0});
    }
}

function startIntro()
{
    // replace intro with flash loader
    if (!document.cookie.match("user=HCP")) {
        introOptions.pause = "true";
    }
    else if (document.cookie.match('skipIntro=true')) {
        introOptions.skip = "true";
    }
    //console.log(introOptions);

    swfobject.embedSWF("/html/flash/intro/intro.swf", "intro", "970", "275", "9.0.0", "/html/javascript/lib/expressInstall.swf", introOptions,{wmode:"transparent", allowScriptAccess:"always" });
}

function startImageRotation ()
{
    // options of the animation
    var content     = 'text';
    var index       = 0;
    var images      = ['/html/images/intro/pic0.jpg','/html/images/intro/pic1_1.jpg'];
    var transition  = 0.5;
    var appearOption = {
        duration:1.0,
        from:0,
        to:1
    };

    function showImage()
    {
        if (index < images.length) {
            //console.log("insert: "+images[index])
            $('image').insert({
                bottom: new Element('img', {
                    src   : images[index],
                    style : 'display:none;z-index:' + (index*2),
                    id    : 'pic' + index
                })
            });
            $('pic' + index).appear(appearOption);
            ++index;
            showImage.delay(transition);
        }
        else {
            postIntro();
        }
    }

    function startAnimation()
    {
        $(content).appear(appearOption);
        showImage.delay(transition);
    }

    // initialize animation
    if($('start')) {
        $('start').appear({
            duration:0.25,
            from:0,
            to:1
        });
    }
    if($(content)) {
        startAnimation.delay(2);
    }
}


// reset the homepage to the first state, called when coming from gateway page.
function resetHomepage() {
    startImageRotation();
}

Event.observe(window, 'load', function() {
    preloadImages('/html/images/xa-sprite.png', '/html/images/intro/pic0.jpg', '/html/images/intro/pic1_1.jpg', panelImageDefault, panelNoFlash, panelImageBlank);
    /*
    panelImages.each(function (src,nr) { if (!nr) { var img = new Image(); img.src = src; } });

    var imagePreload1 = new Image();
    imagePreload1.src = panelImageDefault;

    var imagePreload2 = new Image();
    imagePreload2.src = panelImageBlank;
    imagePreload2.onload = startImageRotation;
    */
});

document.observe('dom:loaded', function() {
    startImageRotation();
    //init country selector
    //FIXME: jslint reports this line as a problem!
    //new Autocompleter.SelectBox('options');
});

$(document).observe("dom:loaded", function(){
    var tabs,
        prefix = "homepage_",
        linkSuffix = "_link",
        element, link, i;
    //TODO read ids dynamically from tabs list
    //tabs = ["tube", "publications", "benefit_calculator", "clinical_studies"],
    tabs = ["tube", "publications", "event_calendar"];

    if(!window.TabbedContent) {
        return;
    }

    var homepageTabs = new TabbedContent();

    var helpers = {
        activate: function(element, event) {
            if(element) {
                element.addClassName('active');
            }
        },
        deactivate: function(element, event) {
            if(element) {
                element.removeClassName('active');
            }
        }
    };

    for(i=0; i<tabs.length; i++) {
        element = $(prefix + tabs[i]);
        if(!element) {
            continue;
        }
        link = $(element.id + linkSuffix);
        element.hide();
        
        homepageTabs.add(
                link,
                [
                    // content will be shown and hidden
                    {el: element},
                    // nav element will change class
                    {el: link, on: helpers.activate, off: helpers.deactivate}
                ]
        );
    }
    
    // either preselect the tab that is given in the url hash
    if(~tabs.indexOf(location.hash.slice("#homepage_".length))) {
        homepageTabs.start($(prefix + location.hash.slice("#homepage_".length) + linkSuffix));
    } else {
        // or select a random tab
        homepageTabs.start($(prefix + tabs[(Math.random()*tabs.length)|0] + linkSuffix));
    }
});

document.observe("dom:loaded", CLAIMS_SETUP);
function CLAIMS_SETUP() {
    // check dependencies
    if(!window.TabbedContent) {
        return;
    }

    var claimRollTime = 4000,
        startAfter = 0,
        currentClaim = 0,
        claimTimeout = false,
        mouseoverGuard = false,
        claims = [$("claim_0"), $("claim_1"), $("claim_2"), $("claim_3")],
        indicationTabs = new TabbedContent(),
        claimTabs = new TabbedContent(),
        ind, i;

    claims.each(Element.hide);

    if(!('ontouchstart' in document.documentElement)) {
        // prepare the mouseover effects
        for(ind, i = 1; i < 4; i++) {
            ind = $("indication_" + i);
            indicationTabs.add(
                ind,
                [
                    {el:$("claim_" + i), on: fadein, off: fadeout}
                ],
                false
            );
            ind.observe("mouseout", mouseout);
            ind.observe("mouseover", mouseover);

        }
    }

    // prepare the animation
    claimTabs.add(claims[0], [{el: claims[0], on: fadein, off: Element.hide}], false);
    for(i = 1; i < 4; i++) {
        claimTabs.add(
            claims[i],
            [
                {el: claims[i], on: fadein, off: Element.hide},
                {el: $("indication_" + i), on: highlightOn, off: highlightOff}
            ],
            false
        );
    }

    startAnimation();

    ////////////
    // helpers
    ////////////
    function mouseout(){
        mouseoverGuard = false;
        cancelEffects();
        claimTimeout = setTimeout(startAnimation, 100);
    }
    function mouseover() {
        clearTimeout(claimTimeout);
        if(mouseoverGuard) {
            return;
        }
        cancelEffects();
        indicationTabs.activate(this);
        mouseoverGuard = true;
    }
    function fadein(el, event) {
        var effect = new Effect.Appear(el, {duration: 0.30, queue: {position: 'end', scope: 'indications'}});
    }
    function fadeout(el, event) {
        var effect = new Effect.Fade(el, {duration: 0.10, queue: {position: 'end', scope: 'indications'}});
    }
    function cancelEffects() {
        Effect.Queues.get("indications").invoke("cancel");
        if(claimTimeout !== false) {
            clearTimeout(claimTimeout);
            claimTimeout = false;
            fadeout(claims[0]);
            [
                $("indication_1")
               ,$("indication_2")
               ,$("indication_3")
            ].each(function(el){
                el.removeClassName("hover");
            });
        }
    }
    function highlightOn(el, event){
        if($(el)) {
            $(el).addClassName('hover');
        }
    }
    function highlightOff(el, event) {
        if($(el)) {
            $(el).removeClassName('hover');
        }
    }
    function startAnimation() {
        currentClaim = 0;
        claimTimeout = setTimeout(nextClaim, startAfter);
    }
    function nextClaim() {
        claimTabs.activate(claims[currentClaim]);
        currentClaim = (currentClaim + 1) % 4;
        clearTimeout(claimTimeout);
        claimTimeout = setTimeout(nextClaim, claimRollTime);
    }
    /////////////
}

