/**
 * DekaBank JavaScript
 * Copyright (c) 2009, 2011 Namics (Deutschland) GmbH. All rights reserved.
 * Code licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */


/**
 * Firebug console.log
 * @usage $.log('Message');
 */
jQuery.log = jQuery.fn.log = function (msg) {
      if ( typeof window.console !== 'undefined' && typeof window.console.log !== 'undefined' ) {
         console.log("%s: %o", msg, this);
      }
      return this;
};

/**
 * JavaScript Flash Detection Library (Flash Detect)
 * @license http://www.featureblend.com/license.txt
 * @see http://www.featureblend.com/javascript-flash-detection-library.html
 */
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}
return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";

var DEKA = {
    // Key definitions
    key_tab: 9,
    key_enter: 13,
    key_esc: 27,
    key_space: 32,

    key_pageup: 33,
    key_pagedown: 34,
    key_end: 35,
    key_home: 36,
    key_left: 37,
    key_up: 38,
    key_right: 39,
    key_down: 40,

    key_minus: 86,
    key_plus: 93,
    key_add: 132,
    key_substract: 140,

    volume: Array(), aGlossaryTime: Array(),

    swfParams: {
        allowScriptAccess:'always', // 'sameDomain'
        menu:'false',
        quality:'high',
        salign:'lt',
        scale:'noScale',
        wmode:'transparent'
    },

    // Initialize
    init: function() {

        var that = this;

        // Show items that are only available with JavaScript, add class "small" | "wide" if there's (not) enough room
        DEKA.addClassToBody();

        // Show page functions if available
        DEKA.showPageFunctions();

        // Setup for accordion menus
        DEKA.accordionInit();

        // Init tablists
        DEKA.tablistInit();

        // Set event listeners to input elements with default text
        $( 'input.hasDefault' ).blur( DEKA.inputDefaults ).focus( DEKA.inputDefaults ).click( DEKA.inputDefaults );

        // Set event listeners to market buttons
        $( '.marketbuttons button' ).bind( 'mouseover mouseout focus blur', DEKA.marketHover ).click( DEKA.marketClick );

        // Set event listener on contact form select
        $( 'select.ctype' ).bind( 'focus blur change', DEKA.onContactTypeChange );

        $( 'button.downloadbuttonmarker' ).bind('click', DEKA.checkDownloadTicked );

        // Set focus on glossary item
        DEKA.setGlossaryFocus();

        // Add abbr element in IE 6-7
        document.createElement('abbr');

        // Ignore annoying tooltips for alt text in IE
        $( 'img' ).not( '[title]' ).attr( 'title', '' );

        // Add pseudo hover to buttons
        DEKA.initIEButtonHover();

        // Add proprietary way to add rounded corners
        if ( typeof isVML !== 'undefined' ) {
            // Add rounded corners
            DEKA.ieRoundedCorner();
        }

        // Configure lightbox
        DEKA.configLightbox();

        // Embed audioplayers via swf-object
        DEKA.addAudioPlayers();

        // Embed intro visual player via swf-object        
        DEKA.addIntroVisualPlayers();

        // Load glossary items
        DEKA.setInfoListeners();
        DEKA.loadGlossaryTerms();

        // Init foldout linklists
        DEKA.foldOutInit();

        DEKA.goToSelect();

        $('a.expand').click(function(){
            var href = $( this ).attr("href");
            $(href).slideToggle("slow");
            return false;
        });

        $('#content a.switchTab').click(function(event){
            var $item = $(event.target);
            var hash = $item.attr('href').replace(/#t/, "#ti");
            
            DEKA.tabClick(null, $(hash));
        });

        // Set state of IntroVisual
        DEKA.setIntroVisual();
 
        // Make Tables with css class .sortable sortable
        DEKA.makeTableSortable();
    },

    // Show items that are only available with JavaScript
    addClassToBody: function() {
        var aClass = $( 'body' ).attr( 'class' ).match( /(home|podcasts|search)/i );
        var sAddClass = ( aClass ) ? aClass[1] : '';
        $( 'body' ).attr( 'class', 'js ' + sAddClass );
    },

    
    // Show page functions: print, tell-a-friend, bookmark
    showPageFunctions: function() {
        var that = this;
        // Print button
        if ( typeof window.print !== 'undefined' ) {
            $( '#button-print' ).click( function() {
                window.print();
            } ).parent().removeClass( 'inactive' );
        }
        
        // Bookmark button (MS IE)
        if (window.navigator.systemLanguage) {
            // Show bookmark button if IE
            $( '#button-bookmark' ).parent( 'li' ).removeClass( 'inactive' );
            // Get current location
            var loc = window.location;
            // Get current URL
            var url = loc.href;
            // Get page title 
            var title = document.title;
            // Add to Favorites
            $( '#button-bookmark' ).click( function() {
                window.external.AddFavorite( url, title );
            });
        }
        
        // if ( window.external && typeof window.external.AddFavorite !== 'undefined' ) {
            // $( '#button-bookmark' ).click( function(){
                // window.external.AddFavorite( location.href, document.title );
            // } ).parent( 'li' ).removeClass( 'inactive' );
        // }
        
        // IntroVisual button open > close
        $( '#button-visual-control.open' ).live('click', function(){
            $( this ).removeClass( 'open' );
            $( this ).addClass( 'close' );
            $('#introVisual').animate(
                { height: '245' }, // 220 + 25 (2nd-LN) = 245
                { step: function(now) {
                    that.setFlashHeight(now); } }
            );
            if(FlashDetect.installed) {
                DEKA.getFlashContainerId('flashContent').stopVisual();
            }
        });
        // IntroVisual button close > open
        $( '#button-visual-control.close' ).live('click', function(){
            $( this ).removeClass( 'close' );
            $( this ).addClass( 'open' );
            $('#introVisual').animate(
                { height: '595' },
                { step: function(now) {
                    that.setFlashHeight(now); } }
            );
            //DEKA.getFlashContainerId('flashContent').playVisual();
        });
    },
    
    // IntroVisual init functionalities
    setIntroVisual: function() {
        if ( typeof swfobject !== 'undefined' ) {
            $('#introVisual').each( function( i ) {
                var sId            = $( this ).attr( 'id' );
                var selector       = $( '#button-visual-control' );
                var flashContainer = $( '#introVisual' );
                var that           = this;
                
                // Prepare values for cookie
                var COOKIE_NAME    = sId;
                var COOKIE_VALUE   = 'viewed';
                var COOKIE_OPTIONS = { expires: 7, path: '/', domain: '' }
                //$.log('Cookie value: ' + $.cookie(sId) );
                
                // If cookie NOT available
                if ( $.cookie(sId) !== COOKIE_VALUE ) {
                    
                    // Set the cookie
                    $.log('Cookie NOT available! Value: [' + $.cookie(sId) +']');
                    $.cookie(COOKIE_NAME, COOKIE_VALUE, COOKIE_OPTIONS);
                    $.log('Cookie SET! Value: [' + $.cookie(sId) +']');
                    
                    setTimeout(function() {
                        $( flashContainer ).animate(
                            { height: '595' },
                            {
                                step: function(now) {
                                    DEKA.setFlashHeight(now);
                                }
                            },
                            1000
                        );
                    }, 1000 );
                    $( selector ).addClass( 'open' );
                }
                // If cookie IS available
                else {
                    $.log('Cookie IS available! Value: [' + $.cookie(sId) +']');
                    $( selector ).addClass( 'close' );
                    setTimeout(function() {
                        $( flashContainer ).animate(
                            { height: '245' },
                            // {
                                // step: function(now) {
                                    // DEKA.setFlashHeight(now);
                                // }
                            // },
                            1000
                        );
                    }, 1000 );
                }
            });
        }
    },
    
    /**
     * TableSorter 2.0 - Client-side table sorting with ease!
     * Version 2.0.5b
     * @requires jQuery v1.2.3
     * Copyright (c) 2007 Christian Bach
     * Examples and docs at: http://tablesorter.com
     * Dual licensed under the MIT and GPL licenses:
     * http://www.opensource.org/licenses/mit-license.php
     * http://www.gnu.org/licenses/gpl.html
     */
    makeTableSortable: function() {
        // extend the default setting to always include the zebra widget
        $.tablesorter.defaults.widgets = ['zebra'];
        $('.sortable').tablesorter({});
    },
    
    // Accordion setup
    accordionInit: function() {
        var acc = $( '.accordion' );
        var oButton = $( 'button.control' );
        oButton.attr( DEKA.nTabindex(), '0' ).each( function (i) {
            $( this ).attr( 'aria-controls', this.id.replace(/(button-)(.*)/, "acc-$2") );
        } );
        if ( acc[0] && acc[0].addEventListener ) {
            acc.each( function ( i ) {
                // Add event listeners for decent browsers
                acc[i].addEventListener( 'click', DEKA.accordionClick, true );
                acc[i].addEventListener( 'keydown', DEKA.accordionClick, false );
            });
        }
        // Add event listener for IE
        else if ( acc[0] && acc[0].attachEvent ) {
            oButton.bind( 'click', DEKA.accordionClick ).keydown( DEKA.accordionClick );
        }
    },

    // Click on accordion control element
    accordionClick: function( e ) {
        // Normalize event object
        if ( typeof e.type !== 'undefined' ) {
            var event = e || window.event;
        }
        else {
            return false;
        }
        // Set variables
        var oKey = new DEKA.KeyObject( event );
        // Fix for WebKit, traverse to parent button element
        if ( oKey.oTarget.nodeName.toLowerCase() === 'span' ) {
            oKey.oTarget = oKey.oTarget.parentNode;
        }
        var jqTarget = $( oKey.oTarget );
        var sType = event.type, nodeName = oKey.oTarget.nodeName.toLowerCase();
        
        // Do something when the target is a control button
        if ( nodeName === 'button' && jqTarget.hasClass( 'control' ) && ( sType === 'keydown' || sType === 'click' ) ) {
            
            // Click is triggered on mouseclick, enter or space key
            if ( sType === 'click' ) {
                // Open accordion panel
                jqTarget.toggleClass('aOpen').next().slideToggle('fast', function(){
                    // Set aria-expanded attribute true | false
                    DEKA.ariaExpandToggle( jqTarget );
                });
                // Update screenreader buffer
                DEKA.updateBuffer();
                // Prevent event bubbling
                DEKA.stopPropagation(event);
                return false;
            }
            // An arrow key was pressed without the alt-key
            else if ( oKey.bArrowKeys ) {
                // Catch all siblings before and after button
                var prev = jqTarget.prevAll( 'button.control' ), next = jqTarget.nextAll( 'button.control' ), oFocus;
                // Reference to the correct arrays of objects
                var fwd = ( oKey.iKey === DEKA.key_left || oKey.iKey === DEKA.key_up ) ? prev : next;
                var rev = ( oKey.iKey === DEKA.key_left || oKey.iKey === DEKA.key_up ) ? next : prev;
                // Get the element to set focus on
                var oFocus = ( fwd.length ) ? fwd[0] : ( rev.length ) ? rev[ rev.length - 1 ] : jqTarget;
                // Set focus
                oFocus.focus();
                // Prevent event bubbling
                DEKA.stopPropagation(event);
                return false;
            }
            // Home or end key is pressed
            else if ( oKey.iKey === DEKA.key_home || oKey.iKey === DEKA.key_end ) {
                // Get all button children in the right order
                var children = $( this ).children( 'button.control' );
                // Get the element to set focus on
                var oFocus = ( oKey.iKey === DEKA.key_home ) ? children[0] : children[ children.length - 1 ];
                oFocus.focus();
                // Prevent event bubbling
                DEKA.stopPropagation(event);
                return false;
            }
        }
        // Ctrl-Up within a panel moves focus to header
        else if ( sType === 'keydown' && oKey.bCtrlKey && oKey.iKey === DEKA.key_up ) {
            jqTarget.parents( '.acontent' ).prev().focus();
            // Prevent event bubbling
            DEKA.stopPropagation(event);
            return false;
        }
        // Return if event happened on an irrelevant element or wrong key was pressed
        else {
            return;
        }
    },

    // Set aria-expanded attribute
    ariaExpandToggle: function( jqObj ) {
        jqObj.next().attr( 'aria-expanded', jqObj.hasClass( 'aOpen' ) ).toggleClass( 'aOpen' ).find( 'div.glossary' ).hide();
    },

    tablistInit: function() {
        var tabs = $( '.tabs' );
        var oAnchor = $( '.tablist a' );
        oAnchor.each( function (i) {
            $( this ).attr( 'aria-controls', this.href.replace(/.*(#)(.*)/, "$2") ).attr( 'href', this.href.replace(/.*(#tab-)(.*)/, '#t-' + "$2" ) );
        } ).not( '.aOpen' ).attr( DEKA.nTabindex(), '-1' );
        if ( tabs[0] && tabs[0].addEventListener ) {
            tabs.each( function ( i ) {
                // Add event listeners for decent browsers
                tabs[i].addEventListener( 'click', DEKA.tabClick, true );
                tabs[i].addEventListener( 'keydown', DEKA.tabClick, false );
            });
        }
        // Add event listener for IE
        else if ( tabs[0] && tabs[0].attachEvent ) {
            oAnchor.bind( 'click', DEKA.tabClick ).keydown( DEKA.tabClick );
        }
        // Set state if hash is present
        var iframe = document.getElementById( 'jquery-history-iframe' );
        if ( location.hash !== '' || ( iframe && iframe.location.hash !== '' ) ) {
            sHref = ( iframe ) ? iframe.location.hash : location.hash;
            sHref = $( sHref.replace( /(#t-)(.*)/, "#ti-$2" ) );
            DEKA.tabClick( '', sHref );
        }
    },

    // Click on a tab
    tabClick: function( e, obj ) {
        // Normalize event object
        if ( e && typeof e.type !== 'undefined' ) {
            var event = e || window.event;
        }
        else if ( !obj ) {
            return false;
        }
        // Set variables
        var oKey = ( event ) ? new DEKA.KeyObject( event ) : obj, jqTarget = ( obj ) ? obj : $( oKey.oTarget ), sType = ( obj ) ? 'click' : event.type, sId = jqTarget.attr( 'id' );
        o = ( sId ) ? document.getElementById( sId ) : null;
        nodeName = ( o && o.nodeName ) ? o.nodeName.toLowerCase() : '';
        if ( nodeName === 'a' && jqTarget.parent().parent().hasClass( 'tablist' ) && ( sType === 'keydown' || sType === 'click' ) ) {
            // Do something when the target isn't the anchor
            if (sType === 'click' && !jqTarget.hasClass('open')) {
                // Close tab panel
                var openTab = jqTarget.parent().siblings().find('a.open'), sOpenHref = openTab.attr('aria-controls'), sHref = jqTarget.attr('aria-controls');
                openTab.removeClass('open clicked').attr(DEKA.nTabindex(), '-1');
                $('#' + sOpenHref).removeClass('open').attr('aria-expanded', 'false').find( 'div.glossary' ).hide();
                // Open tab panel
                var clicked = (event && event.type === 'click') ? ' clicked' : '';
                jqTarget.addClass('open' + clicked).attr(DEKA.nTabindex(), '0');
                $('#' + sHref).addClass('open').attr('aria-expanded', 'true');
                // Set hash
                sHref = sHref.replace(/(tab\-)(.*)/, "t-$2");
                DEKA.setHash( sHref );
                // Set focus
                jqTarget.focus();
                // Update screenreader buffer
                DEKA.updateBuffer();
                // Prevent event bubbling
                DEKA.stopPropagation(event);
                return false;
            }
            // Move open tab with arrow keys
            else if (oKey.bArrowKeys) {
                // Catch all tabs before and after current tab
                var prev = jqTarget.parent().prevAll('li').find('a'), next = jqTarget.parent().nextAll('li').find('a'), oFocus;
                // Reference to the correct arrays of objects
                var fwd = (oKey.iKey === DEKA.key_left || oKey.iKey === DEKA.key_up) ? prev : next;
                var rev = (oKey.iKey === DEKA.key_left || oKey.iKey === DEKA.key_up) ? next : prev;
                // Get the element to set focus on
                var oFocus = (fwd.length) ? fwd[0] : (rev.length) ? rev[rev.length - 1] : jqTarget;
                DEKA.tabClick(event, $(oFocus));
                // Prevent event bubbling
                DEKA.stopPropagation(event);
                return false;
            }
        }
        // Ctrl-Up within a panel moves focus to header
        else if ( sType === 'keydown' && oKey.bCtrlKey && oKey.iKey === DEKA.key_up ) {
            jqTarget.parents( '.tabs' ).find( '.tablist a.open' ).focus();
            // Prevent event bubbling
            DEKA.stopPropagation( event );
            return false;
        }
        // Return if event happened on an irrelevant element or wrong key was pressed
        else {
            return;
        }
    },

    // Hover for market buttons on home page
    marketHover: function( e ) {
        if (isBadIE) {
            var obj = $(this);
            if (typeof e.type !== 'undefined') {
                var event = e || window.event;
            }
            if (event.type === 'mouseover' || event.type === 'focus') {
                obj.parent().addClass('hover');
            }
            else {
                obj.parent().removeClass('hover');
            }
        }
    },
  
    // Click on a market button on home page: change image URL
    marketClick: function( e ) {
        var obj = $( this );
        // Get image object
        var oImg = obj.parent().parent().siblings( '.marketgraph' );
        oImg = oImg.children();
        // Normalize event object
        if ( typeof e.type !== 'undefined' ) {
            var event = e || window.event;
        }
        if ( event.type === 'click' ) {
            obj.focus();                                                          // Focus on button
            obj.parent().siblings().removeClass( 'hover clicked' );               // Remove highlight from other buttons
            obj.parent().addClass( 'hover clicked' );                             // Set highlight on clicked button
            var val = obj.attr( 'class' ).replace( /\s(hover)/, '' );             // get the value from the class because IE6 doesn't get val()
            var param = ( val === 'type1' ) ? 'deka004.jsp?' : 'deka006.jsp?id_notation=';       // set params
            //alert ("oImg.attr(src): " + oImg.attr( 'src' ));
            var src = ( val === 'type1') ? '/financial/' + param + val : '/financial/' + param + val;
            //alert ("val: " + val + " param: " + param + " Source: " + src);
            ( val === 'type1' ) ? oImg.css({'width':'176px', 'height':'66px', 'top':'0', 'left':'0px'}) : oImg.css({'width':'190px', 'height':'73px', 'top':'-4px', 'left':'-10px'});
            oImg.attr( 'src', src );                                              // Replace image
        }
    },

    // Select type change in contact form
    onContactTypeChange: function( e ) {
        // Normalize event object
        if ( typeof e.type !== 'undefined' ) {
            var event = e || window.event;
        }
        var obj = $( this );
        var sVal = obj.find( ':selected' ).val();
        var oContext = obj.parents( 'form' );
        switch ( sVal ) {
            case '1': // Complaint
                oContext.find( 'fieldset.complaint' ).slideDown( 'fast' );
                oContext.find( 'p.ombud' ).slideUp( 'fast' );
                oContext.find( '#birthd_area' ).slideDown( 'fast' );
                DEKA.updateBuffer();
                break;
            case '6': // Ombudsmann
                oContext.find( 'p.ombud' ).slideDown( 'fast' );
                oContext.find( 'fieldset.complaint' ).slideUp( 'fast' );
                oContext.find( '#birthd_area' ).slideUp( 'fast' );
                DEKA.updateBuffer();
                break;
            default:
                oContext.find( 'p.ombud' ).slideUp( 'fast' );
                oContext.find( 'fieldset.complaint' ).slideUp( 'fast' );
                DEKA.updateBuffer();
                break;
        }
    },

    // Set focus on glossary items
    setGlossaryFocus: function() {
        var oTable = $( 'table.glossary' );
        if ( oTable.length > 0 ) {
            if ( location.hash !== '' ) {
                $( location.hash ).addClass( 'focus' );
            }
            if ( isBadIE ) {
                oTable.find( 'td' ).bind( 'mouseover mouseout focus blur click', DEKA.setGlossaryIEClass );
            }
        }
    },

    setGlossaryIEClass: function( e ) {
        // Normalize event object
        if (typeof e.type !== 'undefined') {
            var event = e || window.event;
        }
        if ( event.type === 'click' ) {
            $( this ).toggleClass( 'focus' ).parent().siblings().find( 'td' ).removeClass( 'focus' );
        }
        else {
            $( this ).toggleClass( 'hover', event.type === 'mouseover' || event.type === 'focus' );
        }
    },

    // Toggle between input field defaults and selected input text
    inputDefaults: function( e ) {
        // Normalize event object
        if ( typeof e.type !== 'undefined' ) {
            var event = e || window.event;
        }
        else {
            return false;
        }
        // Get default value from hidden input element
        var sDefaultValue = $( '#' + this.id + '-default' ).val();
        // If field is empty on blur, fill with default value
        if ( event.type === 'blur' && $( this ).val() === '' ) {
            $( this ).val( sDefaultValue ).addClass( 'default' );
            return true;
        }
        // field is clicked on
        else if ( event.type === 'click' && $( this ).val() === sDefaultValue ) {
            $( this ).val( '' ).removeClass( 'default' );
            return false;
        }
        // Field receives focus
        else if ( event.type === 'focus' ) {
            $( this ).select();
            return true;
        }
    },

    // Add :hover and :focus for buttons on IE
    initIEButtonHover: function() {
        if ( isBadIE ) {
            $( 'button' ).bind( 'mouseover focus', function() {
                $( this ).addClass('hover');
            }).bind( 'mouseout blur', function() {
                $( this ).removeClass('hover');
            });
        }
    },

    addAudioPlayers: function(){
        if ( typeof swfobject !== 'undefined' ) {
            $('#content a.media-audio').each( function( i ) {
                var sId = $( this ).attr( 'id' );
                var flashvars = {
                    mediadata: $(this).attr('href'),
                    autoplay: false,
                    controlsbg: false // false = hide background
                };
                var attributes = {
                    id: sId
                };
                swfobject.embedSWF( '/media/flash/DekaAudioPlayer.swf', sId, '205', '33', '9.0.124', '/media/expressInstall.swf', flashvars, DEKA.swfParams, attributes );
            });
        }
    },

    addIntroVisualPlayers: function(){
        if ( typeof swfobject !== 'undefined' ) {
            // $.log('addIntroVisualPlayers()');
            $('#introVisual').each( function( i ) {
                var sId = $( this ).attr( 'id' );
                var flashvars = {
                    mediadata:$(this).attr('data-source'),
                    autoplay:false,
                    controlsbg:false,
                    previewimagedata:$(this).attr('data-preview')
                };
                var attributes = {
                    id: 'flashContent'
                };
                swfobject.embedSWF('/media/flash/DekaVideoPlayerIntroVisual.swf', attributes.id, 995, 560 + 34, '9.0.124', './media/expressInstall.swf', flashvars, DEKA.swfParams, attributes);
            });
        }
    },

    // Rounded tab corners for IE
    ieRoundedCorner: function() {
        $( '.tablist li' ).each( function(i) {
            var obj = $( this );
            // Create two containers
            var borderRadiusLeft = document.createElement( 'span' ), borderRadiusRight = document.createElement( 'span' );
            borderRadiusLeft.className = 'borderRadiusLeft';
            borderRadiusRight.className = 'borderRadiusRight';
            obj.append( borderRadiusLeft ).append( borderRadiusRight );
        } );
    },

    /**************************** 
     * Glossary layer functions *
     ****************************/

    // Dynamically load glossary terms
    loadGlossaryTerms: function() {
        $( 'a.glossary' ).each( function( i ) {
            var obj = $( this ), sHref = obj.attr( 'href' ), sId = '#g' + (i + 1);
            // Load glossary terms
            $.get( sHref, 'id=' + (i + 1), function( data ) {
                if ( data ) {
                    obj.after( data ).attr( 'href', sId );
                    var oTarget = $( sId );
                    // Bind events
                    obj.bind( 'mouseenter focus click', { target: oTarget, id: sId }, DEKA.displayGlossaryTerms )
                        .bind( 'blur mouseleave', { target: oTarget, id: sId }, DEKA.setGlossaryTimer )
                        .attr( 'aria-controls', sId );    
                }
            });
        });
    },

    // Set the event listeners for the form info icons
    setInfoListeners: function() {
        $( 'a.info' ).each( function( i ) {
            var obj = $( this ), sId = obj.attr( 'href' ), oTarget = $( sId );
            // Bind events
            obj.bind( 'mouseenter focus click', { target: oTarget, id: sId }, DEKA.displayGlossaryTerms )
                .bind( 'blur mouseleave', { target: oTarget, id: sId }, DEKA.setGlossaryTimer )
                .attr( 'aria-controls', sId );
        });
    },

    // Show glossary term boxes
    displayGlossaryTerms: function( event ) {
        var oTarget = event.data.target, obj = $( this );
        DEKA.clearGlossaryTimer( DEKA.aGlossaryTime[ event.data.id ] );
        // Position the element
        aPosition = obj.position();
        iMarginTop = obj.css( 'margin-top' );
        iMarginTop = ( iMarginTop === 'auto' ) ? 0 : parseInt( iMarginTop );
        aParentPos = ( obj.hasClass( 'info' ) ) ? obj.parent().position() : { 'top': 0, 'left': 0 };
        if ( obj.attr( 'id' ) === '' ) {
            aPosition.top = parseInt( aPosition.top ) + 3 + parseInt( aParentPos.top ) + iMarginTop;
            aPosition.left = parseInt( aPosition.left + obj.width() ) + 12 + parseInt( aParentPos.left );
            oTarget.css( { 'left': aPosition.left, 'top': aPosition.top } );    
        }
        // Fade-in of glossary box
        oTarget.fadeIn( 'fast' )
            .bind( 'mouseenter focus', { target: oTarget, id: event.data.id }, DEKA.displayGlossaryTerms )
            .bind( 'blur mouseleave', { target: oTarget, id: event.data.id }, DEKA.setGlossaryTimer );
        if ( obj.attr( 'id' ) === '' && event.type === 'click' ) {
            return false;
        }
    },

    // Set timeout
    setGlossaryTimer: function( event ) {
        // Clear old timeout
        DEKA.clearGlossaryTimer( DEKA.aGlossaryTime[ event.data.id ] );
        // Set new timeout
        DEKA.aGlossaryTime[ event.data.id ] = setTimeout( function() {
            DEKA.hideGlossaryTerms( event.data.target );
        }, 1200 );
    },

    // Clear glossary timeout variable
    clearGlossaryTimer: function( timeout ) {
        clearTimeout( timeout );
    },

    // Fade-out of glossary box
    hideGlossaryTerms: function( oTarget ) {
        var sId = oTarget.attr( 'id' );
        // Fade-out
        oTarget.fadeOut( 'slow' );
    },

    /****************************
     * General helper functions *
     ****************************/
    stopPropagation: function ( event ) {
        if (event) {
            // Prevent scrolling
            if (event.stopPropagation) 
                event.stopPropagation();
            if (event.preventDefault) 
                event.preventDefault();
            event.cancelBubble = true;
            event.returnValue = false;
            return false;
        }
    },

    // Create an object with all event properties
    KeyObject: function( event ) {
        var obj = {
            iKey: event.keyCode,
            bCtrlKey: event.ctrlKey,
            bAltKey: event.altKey,
            bShiftKey: event.shiftKey,
            bArrowKeys: (!event.altKey && (event.keyCode === DEKA.key_down || event.keyCode === DEKA.key_up || event.keyCode === DEKA.key_left || event.keyCode === DEKA.key_right)),
            bEnter: (!event.altKey && event.keyCode === DEKA.key_enter),
            oTarget: DEKA.getTarget( event )
        }
        return obj;
    },

    // Normalize tabindex attribute
    nTabindex: function() {
        return ( document.body && document.body.tabIndex === 0 ) ? 'tabIndex' : 'tabindex';
    },

    // Force screen reader buffer update
    updateBuffer: function() {
        if ( $( '#bufferUpdater' ).length === 0 ) {
            $( '#page' ).append( '<form><input type="hidden" value="" id="bufferUpdater" /></form>' );
        }
        $( '#bufferUpdater' ).val( Math.random() );
    },

    // Return the event target element, not a text node
    getTarget: function( event, resolveTextNode ) {
        if (!event) return false;
        var t = event.target || event.srcElement;
        return t;
    },

    // Set URI hash
    setHash: function( sHref ) {
        // Write hash
        if ( typeof window.location.hash !== 'undefined' ) {
            window.location.hash = sHref;
        } else {
            location.hash = sHref;
        }
        
        // Update IE<8 History
        if ( isBadIE ) {
            var iframe = $( '#jquery-history-iframe' );
            if ( iframe.length === 0 ) {
                $('<iframe id="jquery-history-iframe" style="display: none;"></$iframe>').prependTo(document.body)[0];
            }
            iframe = document.getElementById( 'jquery-history-iframe' );
            // Create history entry
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.close();
            iframe.contentWindow.document.location.hash = sHref;
        }
        return false;
    },

    /**
     * nyroModal Mediabox (Lightbox)
     * 
     * @see http://nyromodal.nyrodev.com/
     * @see http://nyromodal.nyrodev.com/wiki/index.php/Main_Page
     */
    configLightbox: function(){
        // Change the default settings
        $(function() {
            $.nyroModalSettings({
                //debug: true,
                bgColor: '#000', // 50% black opacity is set in showBackground()
                showLoading: true,
                minWidth: 1,
                minHeight: 1,
                wrap: {
                    div: '<div class="mediabox"></div>',
                    ajax: '<div class="mediabox"></div>',
                    form: '<div class="mediabox"></div>',
                    formData: '<div class="mediabox"></div>',
                    image: '<div class="mediabox"></div>',
                    swf: '<div class="mediabox"></div>',
                    iframe: '<div class="mediabox"></div>',
                    iframeForm: '<div class="mediabox"></div>',
                    manual: '<div class="mediabox"></div>'
                },
                addImageDivTitle: true,  // Indicate if the div title should be inserted
                setWidthImgTitle: false, // Set the width to the image title
                // close button
                closeButton: '<a href="#" class="closebtn nyroModalClose" title="close">&nbsp;</a>',
                // remove loading and hiding animation
                showLoading: function(elts, settings, callback) {
                    callback();
                },
                showContent: function(elts, settings, callback) {
                    elts.contentWrapper
                        .css({
                            width: settings.width+'px',
                            height: settings.height+'px',
                            marginTop: settings.marginTop+'px',
                            marginLeft: settings.marginLeft+'px'
                        })
                        .show();
                    elts.loading.fadeOut(500, callback);
                },
                hideContent: function(elts, settings, callback) {
                    elts.contentWrapper.hide();
                    callback();
                },
                // Change the background opacity (set opacity to 50%)
                showBackground: function(elts, settings, callback) {
                    elts.bg.css({opacity:0}).fadeTo(500, 0.5, callback);
                }
                //endRemove: function() { alert('modal is gone!'); }
            });
        });

        // 4to3 (400x300)
        $('.mediavideo4to3').click(function(e) {
            e.preventDefault();
            var flashvars = {
                mediadata: $(this).attr('href'),
                autoplay: false,
                controlsbg: true, // true = show background
                previewimagedata: $('.media .preview').attr('src')
            };
            
            var teaserhtml = $('#'+ $(this).attr('id') + "_offline").html();
            var content1 = '<div id="videoplayer"></div>';
            var content2 = '<div class="mediabox-desc">' + teaserhtml + '</div>';
            var content3 = content1 + content2;
            $.nyroModalManual({
                width: 400,
                content: content3
            });
            swfobject.embedSWF('/media/flash/DekaVideoPlayer.swf', 'videoplayer', 400, 300, '9.0.124', '/media/expressInstall.swf', flashvars, DEKA.swfParams);
            return false;
        });

        // 4to3 (640x400)
        $('.mediavideo8to5').click(function(e) {
            e.preventDefault();
            var flashvars = {
                mediadata: $(this).attr('href'),
                autoplay: false,
                controlsbg: true, // true = show background
                previewimagedata: $('.media .preview').attr('src')
            };
            var teaserhtml = $('#'+ $(this).attr('id') + "_offline").html();
            var content1 = '<div id="videoplayer"></div>';
            var content2 = '<div class="mediabox-desc">' + teaserhtml + '</div>';
            var content3 = content1 + content2;
            $.nyroModalManual({
                width: 640,
                content: content3
            });
            swfobject.embedSWF('/media/flash/DekaVideoPlayer.swf', 'videoplayer', 640, 400, '9.0.124', '/media/expressInstall.swf', flashvars, DEKA.swfParams);
            return false;
        });

        // 16to9 (400x225)
        $('.mediavideo16to9').click(function(e) {
            e.preventDefault();
            var flashvars = {
                mediadata: $(this).attr('href'),
                autoplay: false,
                controlsbg: true, // true = show background
                previewimagedata: $('.media .preview').attr('src')
            };
            
            var teaserhtml = $('#'+ $(this).attr('id') + "_offline").html();
            var content1 = '<div id="videoplayer"></div>';
            var content2 = '<div class="mediabox-desc">' + teaserhtml + '</div>';
            var content3 = content1 + content2;
            $.nyroModalManual({
                width: 400,
                content: content3
            });
            swfobject.embedSWF('/media/flash/DekaVideoPlayer.swf', 'videoplayer', 400, 225, '9.0.124', '/media/expressInstall.swf', flashvars, DEKA.swfParams);
            return false;
        });

        // Media Image
        /*
        $('.img .zoom').click(function(e) {
            e.preventDefault();
            var imgName = $(this).attr('href')
            var content1 = '<img src="' + imgName + '" alt="" />';
            $.nyroModalManual({
                content: content1
            });
            return false;
        });
        */
        $('.img .zoom').nyroModal();
    },

    goToSelect: function(){
        var anker = $('#last.select.anker').val();
        if (anker && anker != '' && anker != undefined){
            $('#last.select.anker').val('');        
            document.location.href = anker;
        }
    },

    foldOutInit: function(){
        $('p.foldbutton').each(function(i){
            var obj = $( this );
            var flyout = obj.prev();

            if(flyout.hasClass('foldout')){
                flyout.width(obj.width())
                      .css('top', (obj.position().top - flyout.height() - 5));
                $('a', obj).click(function(){
                    flyout.toggleClass("offscreen");
                    return false;
                });
            }
        });
    },

    checkDownloadTicked: function() {
        if( $('input[name=downloadfile]:checked').length > 0 ) {
            return true;
        }
        return false;
    },

    setFlashHeight: function( value ) {
        if(FlashDetect.installed) {
            DEKA.getFlashContainerId('flashContent').setVisibleHeight(value);
        }
    },

    getFlashContainerId: function( movieName ) {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[movieName];
        } else {
            return document[movieName];
        }
    }
}

$(document).ready(function() {
    DEKA.init();
});

if ( typeof swfobject !== 'undefined' ) {
    /* ExternalInterface for Home flash */
    function changeFlashHeight( value ) {
        $("#flashHomeVisual").animate({
            'height': Number(value)
        }, 'fast');
    }

    /* ExternalInterface for IntroVisual */
    function onIntroVisualPlay() {
        var button = $('#button-visual-control.close');
        
        $('#introVisual').animate(
            {height:'595'},
            {step:function(now)
            {DEKA.setFlashHeight(now);}
        });
    
        $( button ).removeClass( 'close' );
        $( button ).addClass( 'open' );
        
        DEKA.getFlashContainerId('flashContent').setVisibleHeight(value);
    }
}
