/**
 * All In One JavaScript file
 * for homepage only
 * includes the following js files:
 *  - homepage.js
 *  - accordion.js
 *  - cookie.js
 *  - trust.js
 *  - navigation.js
 *  - expand.js
 */

/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * homepage.js
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    // on finish flash loader
    panelImageDefault = "/html/images/home/bg/intro_bg.jpg";
    panelImageBlank   = "/html/images/bg_home.jpg";

    imagePreload     = new Image();
    //imagePreload.src = panelImageDefault;
    imagePreload.src = panelImageBlank;
    introFinished    = false;

    var newsBox = null;
    var innerDiv;

    function addScroller()
    {
        if ( innerDiv.id == "newsBox" )
        {
            if ( newsBox )
            {
                setTimeout( function() { newsBox.initialize(); }, 500 );
            }
            else
            {
                newsBox = new pausescroller( newsTicker, "newsBox", "", 4000 );
            }
        }

        accordionInProgress = false;
    }

    function removeScroller()
    {
        if ( ( innerDiv.id == "newsBox" ) && newsBox )
        {
            newsBox.remove();
        }

        accordionInProgress = false;
    }


    function postIntro()
    {
        introFinished = true;
        //add a cookie to prevent future viewing for 28 days
        var _28days = 28 *24*60*60*1000;
        var date = new Date();
        date.setTime(date.getTime() + _28days);
        document.cookie = 'skipIntro=true; expires=' + date.toGMTString();

        // show welcome background and text
        $('containBg').style.backgroundImage = 'url(' + panelImageDefault + ')';
        $('panel0').style.display = 'block';

        for (var i=1;i<4;++i) {
            var effectDelay = 0.2*(i-1);
            $('mini'+i).addClassName('up');
            Effect.BlindDown($$('#mini' + i + ' a')[0], {delay:effectDelay});
        }

        // add new actions to minis
        $$('.mini').each(function(miniDiv) {
            miniDiv
                .observe('mouseover', miniHoverInitial)
                .observe('mouseout', miniHoverOutInitial);
        });

        //special handling of first "mini"
        //$('mini1').observe('click', panel1Click );

        // if an accordion is not already activated, open the top one [for Array(3)]

        var accordionActive = false;

        if ( $$( '#accordion div h3.on' ).length === 0 ) {
            var initialAccordion = accordionDivs[ 2 ];
            initialAccordion.addClassName( 'on' );
            innerDiv = initialAccordion.parentNode.getElementsByTagName( 'div' )[ 0 ];
            Effect.BlindDown( innerDiv, { delay: 0.0, afterFinish: addScroller } );
        }
    }

    function miniHoverInitial() {
        showPanel(this.id.split('mini')[1]);
    }

    function miniHoverOutInitial() {
        hidePanel(this.id.split('mini')[1]);
    }

    function miniHide(miniNo) {
        var id = 'mini' + miniNo;
        var mini = $(id);
        mini.removeClassName('up');
        mini.effect = Effect.BlindUp($$('#' + id + ' a')[0], {
            queue: { position: 'end', scope: id, limit: 2 }
        });
    }

    // on mini hover
    var panelImages = [
                    ''
                   ,'/html/images/home/bg/panel-vte.jpg'
                   ,'/html/images/home/bg/panel_theheart.jpg'
                   ,'/html/images/home/bg/panel_coagluation_cascade.jpg'
                   ];
    //QUESTION
    panelImages.each(function (element,index) {
        if (index === 0) return;
        imagePreload.src = element;
    });

    function hideAllMinis()
    {
        $$('.mini').each( function (element) {
            element.removeClassName('on');
        });
    }

    // hide all panels but intro panel
    function hideAllPanels()
    {
        $$('.panel').each(function(panel){
            if (panel.id !== 'intro') panel.hide();
        });
    }

    function showPanel(miniNo)
    {

        //highlight button
        hideAllMinis();

        $('mini'+miniNo).addClassName('on');
        // switch introbg
        $('containBg').style.backgroundImage = 'url(' + panelImages[miniNo] + ')';
        // remove intro
        var intro = $('intro');
        if (intro)
            intro.style.visibility='hidden';
        // remove panels
        hideAllPanels();

        // remove vteVideo
        //$('vteVideo').hide();
        //why is it hidden by moving it out of the viewport??
        $('vteVideo').style.left = "-3000px";
        // show panel
        //Effect.Appear($('panel'+miniNo));
        $('panel'+miniNo).style.display = 'block';
    }

    function hidePanel(miniNo) {
        //unhighlight button
        $('mini'+miniNo).removeClassName('on');
        // switch introbg
        if (introFinished) {
            $('containBg').style.backgroundImage = 'url(' + panelImageDefault + ')';
            $('panel0').style.display = 'block';
        } else {
            $('containBg').style.backgroundImage = 'url(' + panelImageBlank + ')';
        }
        // show intro
        if ($('intro')) $('intro').style.visibility='visible';
        // remove panels
        $('panel'+miniNo).hide();
        // hide vteVideo container
        $('vteVideo').style.left = "-3000px";
    }

    // on mini hover while movie playing
    function showPanelInVTE(miniNo) {
        //highlight button
        $('mini2').removeClassName('on');
        $('mini3').removeClassName('on');
        $('mini'+miniNo).addClassName('on');
        // switch introbg
        $('containBg').style.backgroundImage = 'url(' + panelImages[miniNo] + ')';
        // remove panels
        $('panel2').hide();
        $('panel3').hide();
        // remove vteVideo
        $('vteVideo').style.left = "-3000px";
        // show panel one
        $('panel'+miniNo).style.display='block';
    }

    // on mini hover while movie playing
    function hidePanelInVTE(miniNo) {
        //highlight button
        $('mini'+miniNo).removeClassName('on');
        // switch introbg
        $('containBg').style.backgroundImage = 'url(' + panelImageBlank + ')';
        // remove panels
        $('panel'+miniNo).hide();
        // show vteVideo
//      $('vteVideo').style.visibility='visible';
        $('vteVideo').style.left = "10px";
    }

    // on panel one button click
    function panel1Click()
    {
        console.log('panel1click');
        // hide panel
        $('panel1').hide();
        // switch introbg
        if ($('intro')) $('intro').remove();
        $('containBg').style.backgroundImage = 'url(' + panelImageBlank + ')';
        // minimize minis + accordion
        miniHide(1);
        miniHide(2);
        miniHide(3);
        // hide all accordions
        // accordionDivs are initialized in accordion.js (below)
        accordionDivs.each(function(accordion) {
            $(accordion).removeClassName('on');
            $(accordion).addClassName('off');
            Effect.BlindUp($(accordion).parentNode.getElementsByTagName('div')[0]);
        });
        // add new actions to minis
        $$('.mini').each(function(miniDiv) {
            //remove initial event listeners from minis
            miniDiv.stopObserving('mouseover', miniHoverInitial);
            miniDiv.stopObserving('mouseout', miniHoverOutInitial);
            //console.log(1,miniDiv.id);
            if (miniDiv.id == 'mini1') return;
            //console.log(2,miniDiv.id);
            miniDiv.observe('mouseover', function() {
                showPanelInVTE(this.id.split('mini')[1]);
                if (!this.hasClassName('up')) {
                    // cancel any current effects running
                    var queue = Effect.Queues.get(this.id);
                    var startFrame = 0;
                    queue.each(function(effect) {
                        startFrame = 1.0-(effect.currentFrame/100);
                        effect.cancel();
                    });
                    // start new effect
                    this.addClassName('up');
                    this.getElementsByTagName('a')[0].style.height = '72px';  //reset to avoid effect overlap issues.
                    Effect.BlindDown(this.getElementsByTagName('a')[0], {queue: { position: 'end', scope: this.id,  limit: 1 }, from: startFrame});
                }
            });
            miniDiv.observe('mouseout', function(ev) {
                hidePanelInVTE(this.id.split('mini')[1]);
                if (this.hasClassName('up')) {
                    // cancel any current effects running
                    var queue = Effect.Queues.get(this.id);
                    var startFrame = 0;
                    queue.each(function(effect) {
                        startFrame = 1.0-(effect.currentFrame/100);
                        effect.cancel();
                    });
                    // start new effect
                    this.removeClassName('up');
                    Effect.BlindUp(this.getElementsByTagName('a')[0], {queue: { position: 'end', scope: this.id, limit: 1 }, from: startFrame });
                }
            });
        });
        // show vteVideo
        var vteFlashVars = { basePath:"/html/flash/vte-overview/", basePathXML:"/html/xml/" };
        swfobject.embedSWF("/html/flash/vte-overview/videoModule.swf", "vteVideo", "700", "350", "9.0.0", "/html/javascript/lib/expressInstall.swf", vteFlashVars, {wmode:"transparent"});
        $('vteVideo').style.left = "10px";
        $('vteVideo').style.display = 'block';
        //$$('#vteVideo .vmenu')[0].show();
    }

/*
 * disabled for now
 * TODO: reactivate when new videos are online
document.observe('dom:loaded', function(){
    var disAnimMenu = new videoMenu({
        id : 'vidmenu2',
        click : {effect: 1},
        playlist: [
            "/html/video/medres/acute-coronary-syndrome.mp4"
            ,"/html/video/medres/atrial-fibrilation.mp4"
            ,"/html/video/medres/venous-thromboembolism.mp4"
        ],
        items : [{
            id    : "link21",
            clip  : 1
        },{
            id    : "link22",
            clip  : 2
        },{
            id    : "link23",
            clip  : 3
        }],

        backbutton: {
            id    : "showmenu",
            click : function (menu) {
                menu.moved = false; // ??
                menu.toggleNavi({effect:2});
            }
        }
    });
});
*/

/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * accordion.js
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var accordionInProgress = false;
var accordionDivs       = [];

document.observe( 'dom:loaded', registerAccordionEvents );

function registerAccordionEvents()
{
    accordionDivs = $$('#accordion div h3');

    accordionDivs.each(function(accordion) {
        accordion.observe('click', function() {
            if (accordionInProgress) return;

            if ( this.hasClassName( 'on' ) )
            {
                this.removeClassName( 'on' );
                this.addClassName( 'off' );

                accordionInProgress = true;

                innerDiv = this.parentNode.getElementsByTagName( 'div' )[ 0 ];

                Effect.BlindUp( innerDiv, { afterFinish: removeScroller } );
            }
            else
            {
                $$( '#accordion div h3' ).each( function( accordion )
                {
                    if ( accordion.hasClassName( 'on' ) )
                    {
                        accordion.removeClassName( 'on' );
                        accordion.addClassName( 'off' );

                        innerDiv = accordion.parentNode.getElementsByTagName( 'div' )[ 0 ];

                        Effect.BlindUp( innerDiv, { afterFinish: removeScroller } );
                    }
                } );

                this.removeClassName( 'off' );
                this.addClassName( 'on' );

                accordionInProgress = true;

                innerDiv = this.parentNode.getElementsByTagName( 'div' )[ 0 ];

                Effect.BlindDown( innerDiv, { afterFinish: addScroller } );
            }
        });
    });
}

/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * cookie.js
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var Cookie = {
    set: function (name, value, seconds) {
        if (seconds) {
            d = new Date();
            d.setTime(d.getTime() + (seconds * 1000));
            expiry = '; expires=' + d.toGMTString();
        }
        else
            expiry = '';
        document.cookie = name + "=" + value + expiry + "; path=/";
    },
    get: function (name) {
        nameEQ = name + "=";
        ca = document.cookie.split(';');
        for (i = 0; i < ca.length; i++){
            c = ca[i];
            while (c.charAt(0) == ' ')
                c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0)
                return c.substring(nameEQ.length, c.length);
        }
        return null;
    },
    unset: function (name) {
        Cookie.set(name, '', -1);
    }
};


/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * trust.js
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function trustBoxOK () {

    new Effect.Fade($('trust'));
    new Effect.Appear($('audience'));

    Cookie.set('trust', 'dismissed', 86400);

    return false;
}
function audienceOK () {

    new Effect.Fade($('trustFilterNoise'));
    new Effect.Fade($('trustFilter'));
    new Effect.Fade($('audience'));

    // set cookie here if javascript is enabled
    // set cookie so window isn't displayed again for 1 day
    Cookie.set('audience', 'dismissed', 86400);

    return false;
}

//added by eqeee - jleino - 110601
function toHome() {
    var home = '/'; //window.location.protocol + '//' + window.location.host + '/scripts/pages/en/index.php';
    debug(home);
    window.location.href = home;
    return false;
}

/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * navigation.js
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

document.observe('dom:loaded', function(){
 // attach event listeners to child LIs of element with id parentId
    function suckerFish(target) {
        if ($(target) == null) return;
        $$('#' + target + '>li').each( function (item,index) {
            item.observe('mouseover', function (event) {
                this.addClassName('over');
            });
            item.observe('mouseout', function (event) {
                this.removeClassName('over');
            });
        });
    }
    function initSpotLightVideo( data, index ) {
        debug('movie[' + index + ']', data);
        new SpotLightVideo(data);
    }

    suckerFish('nav');
    suckerFish('nav2');
    // set the focus on the search query field
    $$('#nav2 li.last ul')[0]
        .observe('mouseover', function(){ $('query').focus(); });
    
    window.spotLightMovies.each(initSpotLightVideo);
});

//used to get snippets of text for use in javascript files.
function snippet(term) {
    return snippetArr[term];
}

//document.write('<script type="text/javascript" src="/html/json/general.json"><\/script>');
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}

/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * expand.js
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// This file scans nodes for an expand marker "{+}".
// It then adds the remainder into a hidden span, which is revealed when "see more" is clicked.
document.observe("dom:loaded", function () {
    $$('.text').each( function(node) {
        if (node.innerHTML.match(/{\+}/)) {
            var newHTML = node.innerHTML;
            newHTML = newHTML.replace(/{\+}/, ' <a href="#" onclick="Effect.Fade(this);Effect.Appear(this.nextSibling);return false;" class="expandlink">'
                + snippet('miscexpandmore') + '</a><span class="expandblock" style="display:none;"> ');
            newHTML = newHTML.replace(/$/, '</span>');
            node.innerHTML = newHTML;
            if (dtas_updateLinks) dtas_updateLinks();
        }
    });
});
/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * activate countrylist
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
document.observe("dom:loaded", function () {
   new Autocompleter.SelectBox('options');
});


/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * old inline scripts
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

function addHideCountryEvent (element)
{
    element.observe('click',function(event) {
        $$('.countrycontainer').invoke('hide');
        if (swfobject.hasFlashPlayerVersion('7.0.0')) {
            Event.stop(event);
            panel1Click();
        }
   });
}


document.observe('dom:loaded', function() {

    //$$('#miniWrapper #mini1 a').each( addHideCountryEvent );
    //add click eventlistener for all links that should open in a new window
    //replacing deprecated attribute target=_blank
    $$('a.new_page').each( function( element, index){
        element.observe('click',function(event){
            var element = Event.element(event);
            window.open(element.href);
            Event.stop(event);
        });
    });

    $$('a#rssLink').invoke('observe', 'click', function (event) {
//          dcsMultiTrack('WT.cusRSSfeed','1');
    });
});

/**
 * add search tracking parameter
 */
function addWToss(form) {
    dcsMultiTrack("WT.oss", form.q.value);
    return true;
}

/**
 * flashless intro
 */
Event.observe(window, 'load', function() {
    var introText = [
                     ""
                     ,"Deaths attributable to venous thrombosis (VTE) are estimated to exceed the "
                     +"total combined number of deaths from breast cancer, prostate cancer, AIDS and traffic "
                     +"accidents annually."
                     ,"About 1 in 10 deaths that occur in the hospital is caused by pulmonary emboli."
                     ,"Heart attack, a leading cause of deaths in the developed world, is most often triggered by"
                     +"acute trombose formation within a coronary artery."],
        intro = new textFade({
            freeze: 10,
            duration:1,
            id: 'intro_text',
            content: introText,
            finish: postIntro
        });

//    if (location.hash.match('vte')) {
//        if ($('intro')) $('intro').remove();
//        panel1Click();
//    }
//    else
    if (document.cookie.match('skipIntro=true')) {
       intro.skip();
    }
    else {
        intro.start();
        $("skip").observe("click",function(event){
            intro.skip();
        });
    }
});



/***********************************************
* Pausing up-down scroller- © Dynamic Drive (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit http://www.dynamicdrive.com/ for this script and 100s more.
***********************************************/

function pausescroller( content, divId, divClass, delay )
{
    var timer;

    this.content          = content;  // message array content
    this.tickerid         = divId;  // ID of ticker div to display information
    this.delay            = delay;  // Delay between msg change, in miliseconds.
    this.mouseoverBol     = 0;  // Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
    this.hiddendivpointer = 1;  // index of message array for hidden div

    // initial state written to page
//    document.write( '<div id="'+ divId + '" class="' + divClass + '" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'
//        + divId + '1">' + content[0] + '</div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="' + divId + '2">' + content[1] + '</div></div>'
//    )

    var scrollerinstance = this;

//    if (window.addEventListener) // run onload in DOM2 browsers
//        window.addEventListener("load", function(){scrollerinstance.initialize()}, false)
//    else if (window.attachEvent) // run onload in IE5.5+
//        window.attachEvent("onload", function(){scrollerinstance.initialize()})
//    else if (document.getElementById) // if legacy DOM browsers, just start scroller after 0.5 sec
        setTimeout( function() { scrollerinstance.initialize(); }, 500 );
}

// -------------------------------------------------------------------
// initialize()- Initialize scroller method.
// -Get div objects, set initial positions, start up down animation
// -------------------------------------------------------------------

pausescroller.prototype.remove = function()
{
	if(!typeof(timer) === "undefined")
		clearTimeout( timer );
}

pausescroller.prototype.initialize = function()
{
    this.tickerdiv  = document.getElementById( this.tickerid );
    this.visiblediv = document.getElementById( this.tickerid + "1" );
    this.hiddendiv  = document.getElementById( this.tickerid + "2" );

    this.visibledivtop = parseInt( pausescroller.getCSSpadding( this.tickerdiv ) );

    //set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
	if(this.visiblediv) this.visiblediv.style.width = this.tickerdiv.offsetWidth - ( this.visibledivtop * 2 ) + "px";
	if(this.hiddendiv)  this.hiddendiv.style.width  = this.tickerdiv.offsetWidth - ( this.visibledivtop * 2 ) + "px";

    this.getinline( this.visiblediv, this.hiddendiv );

    if(this.hiddendiv) this.hiddendiv.style.visibility = "visible";

    var scrollerinstance = this;

    document.getElementById( this.tickerid ).onmouseover = function() { scrollerinstance.mouseoverBol = 1; }
    document.getElementById( this.tickerid ).onmouseout  = function() { scrollerinstance.mouseoverBol = 0; }

    // clean up loose references in IE
    if ( window.attachEvent )
    {
        window.attachEvent( "onunload", function() { scrollerinstance.tickerdiv.onmouseover = scrollerinstance.tickerdiv.onmouseout = null } );
    }

    setTimeout( function() { scrollerinstance.animateup(); }, this.delay );
}


// -------------------------------------------------------------------
// animateup()- Move the two inner divs of the scroller up and in sync
// -------------------------------------------------------------------

pausescroller.prototype.animateup=function()
{
	if(!this.hiddendiv || !this.visiblediv) return;
	
    var scrollerinstance=this
    if (parseInt(this.hiddendiv.style.top)>(this.visibledivtop+5))
    {
        this.visiblediv.style.top=parseInt(this.visiblediv.style.top)-5+"px"
        this.hiddendiv.style.top=parseInt(this.hiddendiv.style.top)-5+"px"
        timer = setTimeout(function(){scrollerinstance.animateup()}, 50)
    }
    else
    {
        this.getinline(this.hiddendiv, this.visiblediv)
        this.swapdivs()
        timer = setTimeout(function(){scrollerinstance.setmessage()}, this.delay)
    }
}

// -------------------------------------------------------------------
// swapdivs()- Swap between which is the visible and which is the hidden div
// -------------------------------------------------------------------

pausescroller.prototype.swapdivs=function()
{
    var tempcontainer=this.visiblediv
    this.visiblediv=this.hiddendiv
    this.hiddendiv=tempcontainer
}

pausescroller.prototype.getinline=function(div1, div2)
{
    if(div1) div1.style.top=this.visibledivtop+"px"
    if(div2) div2.style.top=Math.max(div1.parentNode.offsetHeight, div1.offsetHeight)+"px"
}

// -------------------------------------------------------------------
// setmessage()- Populate the hidden div with the next message before it's visible
// -------------------------------------------------------------------

pausescroller.prototype.setmessage=function()
{
    var scrollerinstance=this
    if (this.mouseoverBol==1) // if mouse is currently over scoller, do nothing (pause it)
        setTimeout(function(){scrollerinstance.setmessage()}, 100)
    else
    {
        var i=this.hiddendivpointer
        var ceiling=this.content.length
        this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
        this.hiddendiv.innerHTML=this.content[this.hiddendivpointer]
        this.animateup()
    }
}

pausescroller.getCSSpadding=function(tickerobj)
{
    // get CSS padding value, if any
    if (tickerobj.currentStyle)
        return tickerobj.currentStyle["paddingTop"]
    else if (window.getComputedStyle) // if DOM2
        return window.getComputedStyle(tickerobj, "").getPropertyValue("padding-top")
    else
        return 0;
}

