
// ==================================================================================================================
// Set up KONZ Movie Box
// ==================================================================================================================

var MovieBox = Class.create({

    setOptions: function(options) {
        this.options = {
            increments: null,
            duration: .5
        };
        Object.extend(this.options, options || {});
    },

    initialize: function(movieBox, options) {
        this.setOptions(options);
        this.mvBox          = movieBox;
        this.mvContainer    = movieBox.down('.movie').down('div');
        this.mvSelector     = movieBox.down('.movie-selector');
        this.mvInfo         = movieBox.down('.movie-info');
        this.slideContainer = this.mvSelector.down('ul');
        this.triggers       = this.mvSelector.down('.slide-content').select('a');
        this.slideContainer.style.top = 0; // that's important!
        this.setup();
    },

    setup: function() {
        // generate and add random ID, for the case that there are more than one Movie Boxes on a page
        var ID_suffix       = Math.floor(Math.random() * 101);
        var mvContainerID   = 'flashcontent-' + ID_suffix;
        this.mvContainer.id = mvContainerID;
        this.mvSelector.addClassName('enhanced');
        // Set up the movie-selector slider
        this.init_slider();
        // Set up Tooltip HTML
        this.init_tooltipHTML(triggers);
        // Load first movie on pageload
        this.SWF_load();
        // Re-Load other movies on click event
        var triggers = this.triggers;
        var myClass = this;
        triggers.each(function(trigger) {
            trigger.observe('click', this.SWF_reload.bindAsEventListener(trigger, triggers, mvContainerID, myClass));
        }.bind(this));
    },

    // Preload the first movie when page has loaded
    SWF_load: function() {
        var flashContainer  = $(this.mvContainer.id);
        var first_item      = this.mvSelector.down('ul').select('a')[0];
        var fileSource      = first_item.getAttribute('href');
        // Get Objects Metadata
        var json            = first_item.getAttribute('data-json').evalJSON();
        var imageSrc        = json.preview_src;
        // disable noscript warning
        flashContainer.down('.noscript').hide();
        // Show noflash warning
        if (!(swfobject.hasFlashPlayerVersion("9.0.0"))) {
            flashContainer.down('.noflash').show();
        }
        this.insertFlash(flashContainer.id, fileSource, imageSrc);
        first_item.addClassName('active');
    },

    // Load new movie when selected by click
    SWF_reload: function(event, triggers, mvContainerID, myClass) {
        Event.stop(event);
        var flashContainer  = $(mvContainerID);
        var fileSource      = this.getAttribute('href');
        var infoContainer   = myClass.mvInfo;
        var json            = this.getAttribute('data-json').evalJSON();
        var imageSrc        = json.preview_src;
        var infoText        = json.infotext;
        var infoHeading     = this.down('img').getAttribute('alt');

        infoContainer.firstDescendant().update(infoHeading);
        infoContainer.down('p').update(infoText);

        myClass.insertFlash(flashContainer.id, fileSource, imageSrc);
        triggers.invoke('removeClassName', 'active');
        this.addClassName('active');
    },

    insertFlash: function(id, fileSource, imageSrc) {
        var flashvars = {
            'image': imageSrc,
            'file': fileSource,
            'width': 400,
            'height': 225,
            'displayheight': 225
        }
        swfobject.embedSWF("swf/flvplayer.swf", id, 400, 225, "9.0.0", false, flashvars);
    },

    // ==================================================================================================================
    // Set up Movie Selector tooltips

    // Build Tooltip HTML and register Eventhandlers
    init_tooltipHTML: function() {
        var tooltip_HTML = new Element('div', {id: 'tooltip'}).update(new Element('p')).hide();
        document.body.appendChild(tooltip_HTML);
        this.registerTipHandlers();
    },

    registerTipHandlers: function() {
        var myClass = this;
        this.triggers.each(function(trigger) {
            trigger.observe('mouseover', myClass.showTooltip.bindAsEventListener(trigger, myClass));
        });
    },

    updateTipPosition: function(event, tip) {
        var x = Event.pointerX(event);
        var y = Event.pointerY(event);
        tip.setStyle({
            position: 'absolute',
            left: (x + 20) + 'px',
            top: (y - 10) + 'px'
        });
    },

    showTooltip: function(event, myClass) {
        var tip = $('tooltip');
        Event.stopObserving(this, 'mouseover');

        if (tip.style.display == 'none') {
            var tiptext = this.down('img').getAttribute('alt');
            tip.down('p').update(tiptext);
            tip.show();

            var x = Event.pointerX(event);
            var y = Event.pointerY(event);
            tip.setStyle({
                position: 'absolute',
                left: (x + 20) + 'px',
                top: (y - 10) + 'px'
            });
        }
        // Tooltip to move with the Cursor
        this.observe('mousemove', myClass.updateTipPosition.bindAsEventListener(this, tip));
        // Event must not appear when mouse leaves link to child element
        this.onmouseout = function(e) {
            if (!e) var e = window.event;
            var tg = (window.event) ? e.srcElement : e.target;
            var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
            while (reltg != tg && reltg.nodeName != 'BODY')
                reltg= reltg.parentNode
            if (reltg == tg) return;
            tip.hide();
            myClass.registerTipHandlers();
        };
    },

    // ==================================================================================================================
    // Set up Movie Selector

    init_slider: function() {
        this.item           = this.mvSelector.down('li');
        this.itemHeight     = this.item.getHeight() + parseInt(this.item.getStyle('margin-bottom'));
        this.maskSize       = this.mvSelector.down('.slide-mask').getHeight();
        this.increments     = this.getIncrements();
        this.scroll_offset  = this.increments * this.itemHeight;
        this.slideControls  = this.mvSelector.down('.slide-controls');
        this.triggerTop     = this.slideControls.down('.slide-up');
        this.triggerBottom  = this.slideControls.down('.slide-down');

        this.triggerTop.addClassName('inactive');
        this.slideControls.select('a').invoke('observe', 'click', this.set_slide_event.bindAsEventListener(this));
    },

    getIncrements: function() {
        // Either it's declared by options
        if (this.options.increments !== null) {
            this.increments = this.options.increments;
        // or increment is set to the number of visible items
        } else {
            this.increments = Math.round(this.maskSize / this.itemHeight);
        }
        return this.increments;
    },

    set_slide_event: function(event) {
        var trigger = Event.element(event);
        Event.stop(event);
        if (trigger.hasClassName('slide-up') && !trigger.hasClassName('inactive')) {
            this.slideUp(trigger);
        } else if (trigger.hasClassName('slide-down') && !trigger.hasClassName('inactive')) {
            this.slideDown(trigger);
        } else return;
    },

    slideDown: function(trigger) {
        var scroll_offset   = this.scroll_offset;
        var lastMargin      = parseInt(this.item.getStyle('margin-bottom'));
        var actual_position = Math.abs(parseInt(this.slideContainer.style.top));
        var max_position    = this.slideContainer.getHeight() - actual_position;
        var maskSize        = this.maskSize;
        var triggerTop      = this.triggerTop;
        var duration        = this.options.duration;
        // Don't scroll farther than to the last element
        var newOffset = this.slideContainer.getHeight() - maskSize - actual_position;
        if (scroll_offset > newOffset) {
            var newInc = Math.round(newOffset / this.itemHeight);
            scroll_offset = this.itemHeight * newInc;
        }
        // Move!
        if (max_position > this.maskSize) {
            new Effect.Move(this.slideContainer, {
                x: 0,
                y: -(scroll_offset),
                mode: 'relative',
                duration: duration,
                queue: {position: 'end', scope: 'movieSlides', limit: 1},
                afterFinish: function() {
                    max_position = max_position - scroll_offset - lastMargin;
                    if (max_position <= maskSize) {
                        trigger.addClassName('inactive');
                    }
                    triggerTop.removeClassName('inactive');
                }
            });
        }
    },

    slideUp: function(trigger) {
        var scroll_offset   = this.scroll_offset;
        var lastMargin      = parseInt(this.item.getStyle('margin-bottom'));
        var slideContainer  = this.slideContainer;
        var actual_position = Math.abs(parseInt(this.slideContainer.style.top));
        var max_position    = this.slideContainer.getHeight() - actual_position;
        var maskSize        = this.maskSize;
        var triggerBottom   = this.triggerBottom;
        var mode            = 'relative';
        var duration        = this.options.duration;
        // Don't scroll farther than to the first element
        var newOffset = this.slideContainer.getHeight() - actual_position - scroll_offset - lastMargin;
        if (newOffset < maskSize) {
            mode = 'absolute';
            scroll_offset = 0;
        }
        // Move!
        if (actual_position != 0) {
            new Effect.Move(this.slideContainer, {
                x: 0,
                y: scroll_offset,
                mode: mode,
                duration: duration,
                queue: {position: 'end', scope: 'movieSlides', limit: 1},
                afterFinish: function() {
                    actual_position = parseInt(slideContainer.style.top);
                    if (actual_position >= 0) {
                        trigger.addClassName('inactive');
                    }
                    triggerBottom.removeClassName('inactive');
                }
            });
        }
    }
});

// ==================================================================================================================
// Accordeons
// ==================================================================================================================

var Accordeon = Class.create({

    setOptions: function(options) {
        this.options = {
            openFirst: true,
            animate: true,
            duration: 1
        };
        Object.extend(this.options, options || {});
    },

    initialize: function(parentEl, triggerClass, targetClass, options) {

        this.setOptions(options);
        this.triggers    = parentEl.select('.'+triggerClass);
        this.targets     = parentEl.select('.'+targetClass);

        if (this.triggers.length == 0) return;
        // Set explicit heights to avoid flickering on animations
        this.setHeights();
        this.targets.invoke('hide').invoke('addClassName', 'closed');
        this.triggers.invoke('addClassName', 'closed');

        if (this.options.openFirst === true) {
            this.targets[0].show().removeClassName('closed');
            this.triggers[0].removeClassName('closed');
        }

        var accClass = this;
        var triggers = this.triggers;
        var targets  = this.targets;
        triggers.each(function(el) {
            el.observe('click', this.changeState.bindAsEventListener(el, triggers, targets, triggerClass, targetClass, accClass));
        }.bind(this));
    },

    setHeights: function() {
        this.targets.each(function(t) {
            var tHeight = t.getHeight();
            t.setStyle({
                height: tHeight + 'px'
            });
        });
    },

    changeState: function(event, triggers, targets, triggerClass, targetClass, accClass) {
        Event.stop(event);
        var trigger = Event.element(event);
        // Anything inside our header was clicked?
        if (!trigger.hasClassName(triggerClass)) {
            trigger = trigger.up('.'+triggerClass);
        }
        // continue only when clicked box is closed 
        if (trigger.hasClassName('closed')) {
            var actual_target = trigger.next('.'+targetClass);
            // Animate?
            if (accClass.options.animate === true) {
                targets.each(function(tgt) {
                    if (tgt.hasClassName('closed')) return;
                    tgt.addClassName('closed');
                    tgt.previous('.'+triggerClass).addClassName('closed');
                    new Effect.BlindUp(tgt, {
                        duration: accClass.options.duration / 2,
                        queue: {position: 'end', scope: 'accMoves', limit: 2}
                    });
                });
                triggers.invoke('addClassName', 'closed');
                trigger.removeClassName('closed');
                new Effect.BlindDown(actual_target, {
                    duration: accClass.options.duration,
                    queue: {position: 'end', scope: 'accMoves', limit: 2},
                    afterFinish: function() {
                        actual_target.removeClassName('closed');
                    }
                });
            } else {
                targets.invoke('hide');
                actual_target.show();
                triggers.invoke('addClassName', 'closed');
                trigger.removeClassName('closed');
            }
        }
        Event.element(event).blur();
    }
});


// ==================================================================================================================
// Build News Area
// ==================================================================================================================

function buildNewsArea() {
    var news_ctr        = $('news');
    var headers         = news_ctr.select('h3');
    var container       = news_ctr.select('.newsbox');
    var newsNav         = new Element('ul', {id: 'news-tabs'});

    headers.each(function(h) {
        var h_content = h.innerHTML;
        Element.insert(newsNav, '<li>'+h_content+'</li>');
        h.remove();
    });
    Element.insert(news_ctr, {top: newsNav});
    container.invoke('addClassName', 'hidden');
    container[0].removeClassName('hidden');
    news_ctr.addClassName('enhanced');
    $$('#news-tabs li')[0].addClassName('active');

    var links = $$('#news-tabs a');
    var myMap = new Hash;

    links.each(function(link, i) {
        myMap.set(link.id, container[i]);
    });

    $$('#news-tabs a').each(function(a) {
        a.observe('click', changeNewsTab.bindAsEventListener(a, links, container, myMap))
    }.bind(this))
}

function changeNewsTab(event, links, container, myMap) {
    Event.stop(event);

    container.invoke('addClassName', 'hidden');
    myMap.get(this.id).removeClassName('hidden');

    $$('#news-tabs li').invoke('removeClassName', 'active');
    this.up('li').addClassName('active');
    this.blur();
}

// ==================================================================================================================
// News Archive
// ==================================================================================================================

var NewsArchive = Class.create({

    initialize: function(archiveBox) {
        this.archiveBox     = archiveBox.down('.head');
        this.years          = archiveBox.select('li.year');
        this.yearSelectors  = archiveBox.select('a.year-selector');
        this.months         = archiveBox.select('ol.month-selector');
        this.currentYear    = this.years.first();

        archiveBox.addClassName('enhanced');
        // Current year is the first in our list
        this.currentYear.addClassName('active');
        // Now, find current month and set it active
        var date = new Date();
        var currentMonth = this.currentYear.select('li')[date.getMonth()];

        currentMonth.addClassName('active');
        this.load_news(currentMonth.down('a'));
        // Set mouseout eventHandlers (on Years)
        this.set_eventHandler(archiveBox);
        // Set all click eventHandlers
        this.archiveBox.observe('click', this.delegateClickEvents.bindAsEventListener(this));
    },

    set_eventHandler: function(archiveBox) {
        // leaving the drop down closes it
        var allFlyouts = archiveBox.select('.year');
        var myClass = this;
        allFlyouts.each(function(list) {
            list.onmouseout = function(e) {
                var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
                if (!reltg.hasClassName('year-selector')) {
                    myClass.hideYears(myClass);
                }
            }
        });

    },

    showYears: function(myClass) {
        myClass.years.invoke('addClassName', 'hover');
    },

    hideYears: function(myClass) {
        myClass.years.invoke('removeClassName', 'hover');
    },

    delegateClickEvents: function(event) {
        // stop for everything but links
        var triggerEl = event.element();
        if (!triggerEl.match('a')) return;
        // Stop all links
        Event.stop(event);
        // get parent AND context object
        var myClass   = this;
        var parentEl = triggerEl.up('li');
        // This is a month
        if (parentEl.up('ol').hasClassName('month-selector')) {
            this.load_news(triggerEl);
        }   // This is a Year, NOT the active one
            else if (parentEl.hasClassName('year') && (!parentEl.hasClassName('active'))) {
                this.changeYear(parentEl, myClass);
        }   // This is the active year, drop down activator
            else if (parentEl.hasClassName('year') && (parentEl.hasClassName('active'))) {
                this.showYears(myClass);
        }
    },

    changeYear: function(el, myClass) {
        var firstMonth = el.down('ol').firstDescendant(); // should give <li>
        // remove all highlighting CSS and set new active Year and Month
        myClass.archiveBox.select('li.active').invoke('removeClassName', 'active');
        myClass.archiveBox.select('li.hover').invoke('removeClassName', 'hover');
        el.addClassName('active'); // active Year
        firstMonth.addClassName('active'); // active Month
        // @TODO: highlighting the standard way is ugly...
        new Effect.Highlight(el.down('ol'));
        myClass.load_news(firstMonth.down('a')); // news of selected month
    },

    load_news: function(el) {
        this.archiveBox.select('.month-selector li').invoke('removeClassName', 'active');
        el.up('li').addClassName('active');
        var URI       = el.href;
        var container = $('newsdetail');
        var spinner = new Element('span', {'class': 'spinner'});
        new Ajax.Updater(container, URI, {
            // @TODO: probably not perfect yet...
            onCreate: function() {
                Element.insert(container, spinner);
            }
        });
    }
});

// ==================================================================================================================
// Enable keyboard navigation
// ==================================================================================================================
// not perfect yet, but works acceptable...

function showSubnav(event) {
    this.up('ul').addClassName('keyboard-active');
}
function hideSubnav(event) {
    this.up('ul').removeClassName('keyboard-active');
}
function toggleSubnav(event) {
    if (this.next('ul') !== undefined) this.next('ul').toggleClassName('keyboard-active');
}
function hideAllSubnavs(event) {
    $('nav').select('ul').invoke('removeClassName', 'keyboard-active');
}

// ==================================================================================================================
// Tax office finder
// ==================================================================================================================

function officeFinderUpdate(event) {
    var formData    = this.serialize();
    var container   = $('result-wrapper');
    var URI         = this.getAttribute('action');

    Event.stop(event);

    new Ajax.Updater(container, URI, {
        parameters: formData,
        onComplete: function() {
            $('tax-office-form').down('form').observe('submit', officeFinderUpdate);
        }
    });
}

// ==================================================================================================================
// Salary calculator
// ==================================================================================================================

function init_calculator() {
    var formElements = $('calculator').down('form').select('input[type=text]', 'select');

    formElements.each(function(el) {
        var value = el.value;
        if (el.match('input')) {
            el.observe('keyup', delayUpdate.bindAsEventListener(el, value));
        } else {
            if (!Prototype.Browser.IE) {
                el.observe('change', updateForm.bindAsEventListener(el, value));
            } else {
                el.observe('click', updateForm.bindAsEventListener(el, value));
            }
        }
    });
}

function delayUpdate(event, value) {
    var timeOut  = window.setTimeout(function() {updateForm(event, value, timeOut)}, 1250);
    // stop previous function call
    if (timeOut) {
        clearTimeout(timeOut-1);
    }
}

function updateForm(event, value, timeOut) {
    var el          = event.element();
    var container   = $('salary-calculator');
    var URI         = container.down('form').getAttribute('action');
    var formData    = container.down('form').serialize();
    var valueOld    = value;
    var valueNew    = this.value;

    // make "xx,00" equal "xx" and vice versa (due to JSP conversion), do nothing if old and new values are the same
    if (el.match('input')) {
        valueOld    = parseFloat(value.gsub(',', '.'));
        valueNew    = parseFloat(el.value.gsub(',', '.'));
    }
    if (valueOld == valueNew) return;

    var focusId     = el.id; // need the ID, cause el doesn't exist anymore after ajax call
    var spinner     = container.down('#spinner');
    spinner.show();

    new Ajax.Updater(container, URI, {
        parameters: formData,
        onComplete: function() {
            init_calculator();
            setup_smoothScrolling();
            // re-set focus on last active element
            if (focusId) {
                $(focusId).focus();
            }
        }
    });
}

// ==================================================================================================================
// Shopping Cart
// ==================================================================================================================

function initCart() {
    // Cart
    var form = $('warenkorb');
    var link = $('update-cart');
    var con  = $('warenkorbForm');
    var URI  = 'warenkorbForm.html';

    form.observe('submit', updateCart.bindAsEventListener(this, form, con, URI));
    link.observe('click', updateCart.bindAsEventListener(this, form, con, URI));

    // Token
    var tform = $('token');
    var tlink = tform.down('button');
    var tcon  = $('enterToken');
    var tURI  = 'enterToken.html';

    tform.observe('submit', updateCart.bindAsEventListener(this, tform, tcon, tURI));
    tlink.observe('click', updateCart.bindAsEventListener(this, tform, tcon, tURI));
}

function updateCart(event, form, container, URI) {
    Event.stop(event);
    var formData  = form.serialize();

    new Ajax.Updater(container, URI, {
        parameters: formData,
        onComplete: function() {
            initCart();
        }
    });
}

function toggleShipping(event) {
    Event.stop(event);
    var trigger = $('shipping-trigger');
    var target  = $('shipping-address');
    var check = $('abweichendeLieferadresse1');
    if (trigger.hasClassName('closed')) {
        check.checked = true;
        new Effect.BlindDown(target, {
            queue: {position: 'end', scope: 'shipping', limit: 1},
            afterFinish: function() {
                trigger.removeClassName('closed');
            }
        });
        check.observe('change',closeShipping);
    } else {
        check.checked = false;
        new Effect.BlindUp(target, {
            queue: {position: 'end', scope: 'shipping', limit: 1},
            afterFinish: function() {
                trigger.addClassName('closed');
            }
        });
    }
}

function closeShipping(event) {
      var trigger = $('shipping-trigger');
      var target  = $('shipping-address');

    if (!trigger.hasClassName('closed')) {
      new Effect.BlindUp(target, {
          queue: {position: 'end', scope: 'shipping', limit: 1},
          afterFinish: function() {
              trigger.addClassName('closed');
          }
      });
      $('abweichendeLieferadresse1').stopObserving('change',closeShipping);  
    }

}


// ==================================================================================================================
// Search
// ==================================================================================================================

function init_searchPagination(parentList) {
    var paginationLinks = parentList.select('.pagination a');
    // Get all paginationLinks
    paginationLinks.each(function(a) {
        var container   = a.up('li[id]');
        var url         = a.href;
        var pars        = a.getAttribute('data-pars');

        a.observe('click', updateSearchResult.bindAsEventListener(a, container, url, pars, parentList));
    });
}

function updateSearchResult(event, container, url, pars, parentList) {
    Event.stop(event);
    if (Event.element(event).hasClassName('inactive')) return;

    new Ajax.Updater(container, url, {
        parameters: pars,
        onComplete: function() {
            init_searchPagination(parentList);
        }
    });
}

// ==================================================================================================================
// Incremental Search
// ==================================================================================================================

function init_incSearch(searchfield) {
    var container = $('incremental-search');
    var spinnerID = 'indicator1';
    var url       = searchfield.up('form').getAttribute('data-url');

    new Ajax.Autocompleter(searchfield, container, url+'_search.html', {
        minChars: 3,
        indicator: spinnerID
    });
}

// ==================================================================================================================
// Smooth Scrolling
// ==================================================================================================================

function setup_smoothScrolling() {
    // @TODO: This is bad for accessibility. No focus on target element, makes keyboard navigation a hassle
    var scrollLinks = $$('a[href^=#]');

    scrollLinks.each(function(sl) {
        // exclude skip nav for accessibility reasons, s.a.
        if (!sl.up(1).match('#skip-nav')) {
            sl.observe('click', smoothScrolling);
        }
    });
}

function smoothScrolling(event) {
    Event.stop(event);
    var target_id = this.hash.substr(1);
    if (target_id != '') { // could happen with the aweful href="#"...
        // There are targets with name attribute as identifier :(
            if (!$(target_id)) {
                var myTarget = $$('a[name='+target_id+']')[0];
                myTarget.id = target_id; // arrghhh
            }
        Effect.ScrollTo(target_id);
    }
}

// ==================================================================================================================
// Initialize SWFObject
// ==================================================================================================================

function init_SWF(container) {
    // disable noscript warning
    container.down('p.noscript').hide();
    var prev_img    = container.down('img');

    var imgSource   = prev_img.getAttribute('src');
    var fileSource  = container.down('a').href;
    var el_width    = prev_img.getAttribute('width');
    var el_height   = prev_img.getAttribute('height');

    var flashvars = {
      image: imgSource,
      file: fileSource,
      width: el_width,
      height: el_height,
      displayheight: el_height
    };

    if (!(swfobject.hasFlashPlayerVersion("9.0.0"))) {
        // Show noflash warning
        container.down('p.noflash').show();
    }
    swfobject.embedSWF('../swf/flvplayer.swf', 'movie-content', el_width, el_height, '9.0.0', false, flashvars);
}

// ==================================================================================================================
// Initialize Shadowbox
// ==================================================================================================================

function openShadowbox(event, opt) {
    Event.stop(event);

    Shadowbox.open({
        content: opt.content,
        player: opt.player,
        width: opt.width,
        height: opt.height
    });
}

// ==================================================================================================================
// Initialize everything
// ==================================================================================================================

function init() {
    // Enable keyboard navigation
    if ($('nav')) {
        $$('#nav li li a').invoke('observe', 'focus', showSubnav);
        $$('#nav > li > a').invoke('observe', 'focus', toggleSubnav);
        $$('#nav li li:last-child a').invoke('observe', 'blur', hideSubnav);
        $$('#nav a').invoke('observe', 'mouseover', hideAllSubnavs);
    }
    // Enable incremental search
    if ($('searchfield')) {
        init_incSearch($('searchfield'));
    }
    // Search Pagination
    if ($('all-results')) {
        init_searchPagination($('all-results'));
    }
    // Smooth Scrolling
    setup_smoothScrolling();
    // Build News Area
    if ($('news')) {
        buildNewsArea();
    }
    // News Archive
    if ($('archive-list')) {
        new NewsArchive($('archive-list'));
    }
    // Activate Sliding Boxes
    if ($('home-stage')) {
        new SlidingBox($('home-stage'), {
            autoslide: true,
            delay: 10
        });
    }
    if ($('shop-stage')) {
        new SlidingBox($('shop-stage'));
    }
    if ($$('.small-slider').length >= 1) {
        $$('.small-slider').each(function(slider) {
            new SlidingBox(slider);
        });
    }
    // KONZ Movies
    if ($$('.konz-tv').length >= 1) {
        $$('.konz-tv').each(function(movieBox) {
            new MovieBox(movieBox);
        });
    }
    // Tax office finder
    if ($('tax-office-form')) {
        $('tax-office-form').down('form').observe('submit', officeFinderUpdate);
    }
    // Salary calculator
    if ($('calculator')) {
        init_calculator();
    }
    // Shopping Cart
    if ($('warenkorb')) {
        initCart();
    }
    // Shipping address
    if ($('shipping-trigger')) {
        if ($('shipping-trigger').hasClassName('stayOpen')) {
            $('shipping-trigger').observe('click', toggleShipping);
            $('abweichendeLieferadresse1').observe('change',closeShipping);
        } else {
            $('shipping-address').hide();
            $('shipping-trigger').observe('click', toggleShipping).addClassName('closed');
        }
    }

    // === Start SWFObjects ==============================

    if ($('movie-content')) {
        init_SWF($('movie-content'));
    }

    // === Start all Shadowboxes ==============================

    // if ($('onse-release-info')) {
    //     var releaseForm = $('onse-release-info');
    //     var target      = releaseForm.getAttribute('action');
    //     releaseForm.observe('submit', openShadowbox.bindAsEventListener(this, {content: target, width: 800, height: 600, player: 'iframe'}));
    // }
    if ($('onse-preview')) {
        var triggers = $('onse-preview').select('a');
        var target  = triggers[0].href;
        triggers.each(function(trig) {
            trig.observe('click', openShadowbox.bindAsEventListener(this, {content: target, width: 800, height: 450, player: 'iframe'}));
        });
    }
    if ($('konz-intro')) {
        var triggers = $('konz-intro').select('a');
        var target  = triggers[0].href;
        triggers.each(function(trig) {
            trig.observe('click', openShadowbox.bindAsEventListener(this, {content: target, width: 800, height: 450, player: 'iframe'}));
        });
    }

    // === Start all Accordeons ==============================

    // Tipp subcategories
    if ($$('.tip-list-header').length >= 1) {
        $$('.subcategory').each(function(subcat) {
            new Accordeon(subcat.down('.link-list'), 'tip-list-header', 'tip-list-body', {openFirst:false, duration:0.2});
        });
    }
    // Tipps
    if ($('tip-categories')) {
        new Accordeon($('tip-categories'), 'tip-cat-header', 'tip-cat-body');
    }
    // FAQ
    if ($$('.faq-list').length >= 1) {
        $$('.faq-list').each(function(faq) {
            new Accordeon(faq, 'faq-question', 'faq-answer', {openFirst: false, duration:0.5});
        });
    }
    // Tax forms
    if ($('tax-forms')) {
        new Accordeon($('tax-forms'), 'tax-form-header', 'tax-form-body');
    }
    // Konz48 Services
    if ($('konz48-services')) {
        new Accordeon($('konz48-services'), 'service-head', 'service-body', {duration:0.5});
    }
    // Konz48 Ablauf
    if ($('konz48-ablauf')) {
        new Accordeon($('konz48-ablauf'), 'service-head', 'service-body', {duration:0.5});
    }
    // Start accordeon for about us
    if ($('ueber-uns-categories')) {
        new Accordeon($('ueber-uns-categories'), 'ueber-uns-cat-header', 'ueber-uns-cat-body');
    }
}

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