/*
	Placeholder for header search field
	nh 20101027
	!! TO DO !! Works, but please rewrite using prototype...
*/
function searchfield_placeholder() {
	var header_searchfield = document.getElementById("searchfield");
	var header_searchfield_placeholder_text = "Suchen";
	header_searchfield.onfocus = function() {
		if (header_searchfield.value == header_searchfield_placeholder_text) {
			header_searchfield.value = "";
			header_searchfield.style.color="#333";
		}
	}
	header_searchfield.onblur = function() {
		if (header_searchfield.value == "") {
			header_searchfield.value = header_searchfield_placeholder_text;
			header_searchfield.style.color="#999";
		}
	}
}

// ==================================================================================================================
// 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();
    }
});

// ==================================================================================================================
// 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() {

    var cartform = $('warenkorb');
    var submitlink = $('update-cart');
    var cartcon  = $('warenkorbForm');
    var URI  = 'warenkorbForm.html';

    var submitCart = function submitCart(ev) {
        console.log('submit cart');
        console.log(ev);
        ev.stop();
        var formData  = cartform.serialize();
        new Ajax.Updater(cartcon, URI, {
            parameters: formData,
            onComplete : function() {
                // we call initCart again to re-attach this event handler after the update
                initCart();
            }
        });
    };

    cartform.observe('submit',submitCart);
    submitlink.observe('click',submitCart);

}

function initTokenForm() {

    // Token
    var tform = $('token');
    if (tform) {
        // the token form may not be displayed, if the page is reloaded after a gutschein is already in the warenkorb
        var tlink = tform.down('button');
        var tcon  = $('enterToken');
        var tURI  = 'enterToken.html';

        var tcomplete = function tcomplete() {
            // we are looking for the errors span to find out if the token was accepted
            var err = $('code.errors');
            if (err)  {
                // the token was not accepted
                // we call initTokenForm again to re-attach event handlers after the update
                initTokenForm();
            } else {
                // token was accepted, we do a complete reload
                // this should make the gutschein show up in the cart and the enter token form to dissapear
                window.location.reload();
            }
        };


        tform.observe('submit',function(ev) {
             ev.stop();
             var formData  = tform.serialize();
             new Ajax.Updater(tcon, tURI, {
                parameters: formData,
                onComplete : tcomplete
          });
        });

        // if a code is already filled in, this means we called the page with a tokenCode as request Parameter
        // we immediately submit the form
        var code = $('code').value;
        if (code) {
            //alert('code = ' + code);
            $('code').value = ''; // we remove the code from the field
            tform.stopObserving(); // unregisters all event handlers for this form
            new Ajax.Updater(tcon,tURI,{
                parameters : {code : code},
                onComplete : tcomplete
            });
        }
    }
}


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);
    }
}

// ==================================================================================================================
// User registration
// ==================================================================================================================

var ACCEPT_TERMS_TRIGGER = 'accept-terms-details-trigger';
var ACCEPT_TERMS_TARGET = 'accept-terms-details';

function toggleAcceptTermsDetails(event) {
    Event.stop(event);
    var target = $(ACCEPT_TERMS_TARGET);
    if (target.hasClassName('closed')) {
        new Effect.BlindDown(target, {
            //queue: {position: 'end', scope: 'shipping', limit: 1},
            afterFinish: function() {
                target.removeClassName('closed');
            }
        });
    } else {
        new Effect.BlindUp(target, {
            //queue: {position: 'end', scope: 'shipping', limit: 1},
            afterFinish: function() {
                target.addClassName('closed');
            }
        });
    }
}

// ==================================================================================================================

function onse_student_verify() {
	if ($F("onse-student-check") == "on" && $F("onse-student-school") != "0") {
		$("onse-student-message").addClassName("onse-student-verified").update("Herzlichen Glückwunsch. Kaufen Sie jetzt die KONZ Online-Steuererklärung (Studentenversion).");
		$("onse-student-purchase").enable().writeAttribute("value", "Jetzt kaufen!");
		$("onse-student-school").disable();
		$("onse-student-check").disable();
	}
}


// ==================================================================================================================
// 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 and search placeholder
    if ($('searchfield')) {
        init_incSearch($('searchfield'));
        searchfield_placeholder();
    }
    // Search Pagination
    if ($('all-results')) {
        init_searchPagination($('all-results'));
    }
    // Smooth Scrolling
    setup_smoothScrolling();

    // Activate Sliding Boxes
    var HOME_PAGE_SLIDER = false;	// Set to false to deactive slider! [changed nh 20110128]
    if ($('home-stage') && HOME_PAGE_SLIDER) {	// changed nh 20110128
        new SlidingBox($('home-stage'), {
            autoslide: false,
            delay: 10
        });
        $('home-stage').addClassName('slide-background');	// changed nh 20110128
    }
    /*
    // nh 20110426-27
    if ($('stage-home-onse-2011-usp-slider')) {
        new SlidingBox($('stage-home-onse-2011-usp-slider'), {
			autoslide: true,
			delay: 5,
			infinite: true,
		//	increments: 1,
        });
    }
    */

	// nh 20110428 (via Jan)
	if ($("onse-student-school")) {
		$("onse-student-school").observe("change", onse_student_verify);
		$("onse-student-check").observe("click", onse_student_verify);
	}

    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();
        initTokenForm();
    }
    // 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');
        }
    }
	// Explanatory note for the 'accept terms' checkbox when registering; nh 20100720,-22
    if ($(ACCEPT_TERMS_TARGET) && $(ACCEPT_TERMS_TRIGGER)) {
		$(ACCEPT_TERMS_TARGET).hide().addClassName('closed');
    	$(ACCEPT_TERMS_TRIGGER).observe('click', toggleAcceptTermsDetails);
	}

    // === 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-landing-page-201105-video')) {
		var target = $('onse-landing-page-201105-video').href;
		$('onse-landing-page-201105-video').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);

