/* $Id: general.js 1798 2012-02-21 14:28:45Z mso $ */
var masterFlyoutTO = false;
var flyOutActive = false;
var filialFinderZoomed = false;
var chart1, chart;
// Gallery Slideshow
function gsWidget() {

    var myRoot = '#gallery_slideshow';
    var isCustom = false, isInline = false;
    var thumbWidth = 88; // Should read that from CSS!
    if (arguments.length) {
        myRoot = arguments[0];
        isCustom = true;
    }

    if (!$(myRoot).length) {
        return false;
    }

    if ($(myRoot).hasClass('inline')) {
        isInline = true;
    }

    var tmbs = $(myRoot + ' .tmb');
    var tmb_prev = $(myRoot + ' .tmb_nav .prev');
    var tmb_next = $(myRoot + ' .tmb_nav .next');
    var foto = $(myRoot + ' .foto img');
    var lightBox = $(myRoot + ' .foto.lightbox');

    if (!isCustom) {
        foto.load(function () { $.fancybox.hideActivity(); } );
    }

    if (!isInline) {
        var foto_prev = $(myRoot + ' .foto_wrapper .prev');
        var foto_next = $(myRoot + ' .foto_wrapper .next');
    }

    var position = $(myRoot + ' .position');
    var total = $(myRoot + ' .total');
    var counter = 0;
    var slots = isInline ? 4 : 1000;
    var tmb_list = $(myRoot + ' .tmb_list ul');

    var widthThumbs = (tmbs.length * thumbWidth);
    var pushPagers = (($(myRoot).width() - widthThumbs) / 2);

    tmb_list.css('width', widthThumbs);
    if (!isInline) {
        tmb_prev.css('left', pushPagers);
        tmb_next.css('right', pushPagers - 30);
    }

    var description = $(myRoot + ' .caption');
    var caption = $(myRoot + ' .fotocaption');

    // Init as open
    $(myRoot + ' .aufzu').addClass('open');
    caption.removeClass('hidden');
    //

    $(myRoot + ' .aufzu').bind('click', function() {
        if (caption.hasClass('hidden')) {
            caption.removeClass('hidden');
            $(this).addClass('open');
        } else {
            caption.addClass('hidden');
            $(this).removeClass('open');
        }
    });

    tmb_prev.addClass('disabled');
    if (!isInline) {
        foto_prev.addClass('disabled');
    }

    tmbs.each(function (intIndex) {
        var preload = new Image();
        preload.src = $(this).attr('href');

        $(this).unbind('click').bind('click', function(e) {
            e.preventDefault();
            foto.attr('src', $(this).attr('href'));
            var myRel = $(this).attr('data-href');
            if (typeof myRel != 'undefined' && lightBox.length > 0) {
                lightBox.attr(
                        {'href': myRel
                        ,'data-delegate': $(this).attr('rel')
                        ,'data-offset' : $(this).attr('data-offset')
                        });
            }

            if (!isCustom) {
                $.fancybox.showActivity();
            }
            counter = intIndex;
            $(myRoot + ' .disabled').removeClass('disabled');
            if (counter == 0) {
                tmb_prev.addClass('disabled');
                if (!isInline) {
                    foto_prev.addClass('disabled');
                }
            }
            if (counter == (tmbs.length - 1) ) {
                tmb_next.addClass('disabled');
                if (!isInline) {
                    foto_next.addClass('disabled');
                }
            }
            tmbs.removeClass('selected');
            tmbs.eq(intIndex).addClass('selected');
            caption.html(description.eq(counter).html());
            return false;
        });
    });

    tmbs.eq(0).click();

    function prevFoto()
    {
        if (counter > 0) {
            counter--;
            tmbs.eq(counter).click();
        }
        if (counter >= (slots - 1) ) {
            tmb_list.css('left', -(counter-(slots-1)) * thumbWidth);
        }
    }

    function nextFoto()
    {
        if (counter < (tmbs.length - 1) ) {
            counter++;
            tmbs.eq(counter).click();
        }
        if (counter > (slots-1) ) {
            tmb_list.css('left', -(counter-(slots-1)) * thumbWidth);
        }
    }

    if (!isInline) {
        foto_prev.unbind('click').click(prevFoto);
        foto_next.unbind('click').click(nextFoto);
    }

    tmb_prev.unbind('click').click(prevFoto);
    tmb_next.unbind('click').click(nextFoto);
}
// Gallery Slideshow

function attachLightbox()
{
    var Me = $(this);
    var fbOptions = {'showNavArrows': false, 'centerOnScroll': true, 'overlayOpacity': 0.9};
    if (Me.hasClass('gallery') || Me.hasClass('video')) {
        fbOptions['titleShow'] = false;
        fbOptions['scrolling'] = 'no';
        if (Me.hasClass('video')) {
            if (/iphone/i.test(navigator.userAgent) || /ip[ao]d/i.test(navigator.userAgent)) {
                fbOptions['showCloseButton'] = false;
            }
            fbOptions['onCleanup'] = function() {
                try {
                    var $maxislider = $('.maxislider');
                    if ($maxislider.hasClass("fade")) {
                        sliderStartInterval();
                    }else {
                        // restart the slider
                        $maxslider.tinycarousel_start();
                    }
                   
                } catch (ex) {
                    /* ignore silently console.log("Exception", ex); */
                }
            }
        }
        if (Me.hasClass('gallery')) {
            fbOptions['showCloseButton'] = true;
            fbOptions['onComplete'] = function() {
                gsWidget('#' + $('#fancybox-content .gs_widget').attr('id'));
                try {
                    $('.maxislider').tinycarousel_stop();
                } catch (e) {
                    /* ignore silently console.log("Exception", e); */
                }
            }
            fbOptions['onCleanup'] = function() {
                try {
                    var $maxislider = $('.maxislider');
                    if ($maxislider.hasClass("fade")) {
                        sliderStartInterval();
                    } else {
                        $maxslider.tinycarousel_start();
                    }
                } catch (e) {
                    /* ignore silently console.log("Exception", e); */
                }
            }           
        }
    }
    Me.fancybox(fbOptions);
    Me.click(function () { return false; });
}

/**
 * @name       Defaultvalue
 * @descripton Gives value to empty inputs
 * @version    1.4.2
 * @requires   Jquery 1.3.2
 * @author Jan Jarfalk, jan.jarfalk@unwrongest.com, janjarfalk (twitter), http://www.unwrongest.com
 * @licens MIT License - http://www.opensource.org/licenses/mit-license.php
 * @param {Function} callback  Callback function
 */
(function($){
    $.fn.extend({
         defaultValue: function(callback) {
            var nativePlaceholderSupport = (function(){
                var i = document.createElement('input');
                return ('placeholder' in i);
            })();

            // Default Value will halt here if the browser
            // has native support for the placeholder attribute
            if (nativePlaceholderSupport) {
                return false;
            }

            return this.each(function(index, element) {
                // Executing Default Value twice on an element will lead to trouble
                if ($(this).data('defaultValued')) {
                    return false;
                }

                var $input             = $(this),
                    defaultValue       = $input.attr('placeholder');
                var callbackArguments  = {'input':$input};

                // Mark as defaultvalued
                $input.data('defaultValued', true);

                // Create clone and switch
                var $clone = createClone();

                // Add clone to callback arguments
                callbackArguments.clone = $clone;

                $clone.insertAfter($input);

                var setState = function() {
                    if ($input.val().length <= 0) {
                        $clone.show();
                        $input.hide();
                    } else {
                        $clone.hide();
                        $input.show().trigger('click');
                    }
                };

                // Events for password fields
                $input.bind('blur', setState);

                // Create a input element clone
                function createClone() {
                    var $el;
                    if ($input.context.nodeName.toLowerCase() == 'input') {
                        $el = $("<input />").attr({'type' : 'text'});
                    } else if ($input.context.nodeName.toLowerCase() == 'textarea') {
                        $el = $("<textarea />");
                    } else {
                        throw 'DefaultValue only works with input and textareas';
                    }

                    $el.attr({
                        'value' : defaultValue,
                        'class' : $input.attr('class')+' empty',
                        'size' : $input.attr('size'),
                        'style' : $input.attr('style'),
                        'tabindex' : $input.attr('tabindex'),
                        'rows' : $input.attr('rows'),
                        'cols' : $input.attr('cols'),
                        'name' : 'defaultvalue-clone-' + (((1+Math.random())*0x10000)|0).toString(16).substring(1)
                    });

                    $el.focus(function() {
                        // Hide text clone and show real password field
                        $el.hide();
                        $input.show();
                        // Webkit and Moz need some extra time
                        // BTW $input.show(0,function(){$input.focus();}); doesn't work.
                        setTimeout(function () {
                            $input.focus();
                        }, 1);
                    });
                    return $el;
                }

                setState();

                if (callback) {
                    callback(callbackArguments);
                }
            });
        }
    });
})(jQuery);

(function($) {

    var defaults = {
        'swipeTolerance': 40
    };

    var touchStatus = function(target, touch) {
        this.target = $(target);
        this.touch = touch;
        this.startX = this.currentX = touch.screenX;
        this.startY = this.currentY = touch.screenY;
        this.eventType = null;
    }
    touchStatus.options = {};
    touchStatus.latestTap = null;

    touchStatus.prototype.move = function(touch) {
        this.currentX = touch.screenX;
        this.currentY = touch.screenY;
    }

    touchStatus.prototype.process = function() {
        var offsetX = this.currentX - this.startX;
        var offsetY = this.currentY - this.startY;
        if(offsetX == 0 && offsetY == 0) {
            this.checkForDoubleTap();
        } else if(Math.abs(offsetY) > touchStatus.options.swipeTolerance && Math.abs(offsetY) > Math.abs(offsetX)) {
            this.eventType = offsetY > 0 ? 'swipedown' : 'swipeup';
            this.target.trigger('swipe', [this])
        } else if(Math.abs(offsetX) > touchStatus.options.swipeTolerance) {
            this.eventType = offsetX > 0 ? 'swiperight' : 'swipeleft';
            this.target.trigger('swipe', [this])
        }
        if(this.eventType) this.target.trigger(this.eventType, [this])
        this.target.trigger('touch', [this])
    }

    touchStatus.prototype.checkForDoubleTap = function() {
        if(touchStatus.latestTap) {
            if((new Date() - touchStatus.latestTap) < 400)
            this.eventType = 'doubletap'
        }
        if(!this.eventType) this.eventType = 'tap'
        touchStatus.latestTap = new Date()
    }

    var swipeEvents = function(elements, options) {
        touchStatus.options = $.extend(defaults, options);
        elements.bind('touchstart', this.touchStart);
        elements.bind('touchmove', this.touchMove);
        elements.bind('touchcancel', this.touchCancel);
        elements.bind('touchend', this.touchEnd);
    }

    swipeEvents.prototype.touchStart = function(evt) {
        var target = this;
        swipeEvents.eachTouch(evt, function(touch) {
            swipeEvents.touches[touch.identifier] = new touchStatus(target, touch);
        })
    }

    swipeEvents.prototype.touchMove = function(evt) {
        swipeEvents.eachTouch(evt, function(touch) {
            var loc = swipeEvents.touches[touch.identifier]
            if(loc) loc.move(touch)
        })
    }

    swipeEvents.prototype.touchCancel = function(evt) {
        swipeEvents.eachTouch(evt, function(touch) {
            swipeEvents.purge(touch, true)
        })
    }

    swipeEvents.prototype.touchEnd = function(evt) {
        swipeEvents.eachTouch(evt, function(touch) {
            swipeEvents.purge(touch)
        })
    }

    swipeEvents.touches = {}
    swipeEvents.purge = function(touch, cancelled) {
        if(!cancelled) {
            var loc = swipeEvents.touches[touch.identifier]
            if(loc) loc.process()
        }
        delete swipeEvents.touches[touch.identifier]
    }

    swipeEvents.eachTouch = function(evt, callback) {
        var evt = evt.originalEvent;
        var num = evt.changedTouches.length;
        for(var i = 0; i < num; i++) {
            callback(evt.changedTouches[i])
        }
    }

    // adds custom events:
    // touch // all events
    // swipe // only swipe* events
    // swipeleft
    // swiperight
    // swipeup
    // swipedown
    // tap
    // doubletap
    $.fn.addSwipeEvents = function(options, callback) {
        if (!callback && jQuery.isFunction(options)) {
            callback = options;
            options = null;
        }
        new swipeEvents(this, options);
        if(callback) this.bind('touch', callback);
        return this;
    }
})(jQuery);

/*
* A bridge between iPad and iPhone touch events and jquery draggable, sortable etc. mouse interactions.
* @author Oleg Slobodskoi
*/
/iPad|iPhone/.test( navigator.userAgent ) && (function( $ ) {

    var proto = $.ui.mouse.prototype,
        _mouseInit = proto._mouseInit;

    $.extend( proto, {
        _mouseInit: function() {
            this.element
                .bind( "touchstart." + this.widgetName, $.proxy( this, "_touchStart" ) );

            _mouseInit.apply( this, arguments );
        },

        _touchStart: function( event ) {
            if ( event.originalEvent.targetTouches.length != 1 ) {
                return false;
            }

            this.element
                .bind( "touchmove." + this.widgetName, $.proxy( this, "_touchMove" ) )
                .bind( "touchend." + this.widgetName, $.proxy( this, "_touchEnd" ) );

            this._modifyEvent( event );

            this._mouseDown( event );

            return false;
        },

        _touchMove: function( event ) {
            this._modifyEvent( event );
            this._mouseMove( event );
        },

        _touchEnd: function( event ) {
            this.element
                .unbind( "touchmove." + this.widgetName )
                .unbind( "touchend." + this.widgetName );
            this._mouseUp( event );
        },

        _modifyEvent: function( event ) {
            event.which = 1;
            var target = event.originalEvent.targetTouches[0];
            event.pageX = target.clientX;
            event.pageY = target.clientY;
        }

    });

})( jQuery );


$.fn.teaserSlider = function() {

    return this.each(function() {
        var Me = $(this);
        var viewPort = Me;
        var Prev = Me.find('.buttons.prev');
        var Next = Me.find('.buttons.next');
        var Stage = Me.find('.overview');
        var theKids = Stage.find('li');
        Me.find('.buttons').addClass('disable');

        var kidCount = 0;
        var skimOffset = 0;
        var kidWidth = 0;
        var stageWidth = 0;
        var visCount = 4; // hard coded for now
        theKids.each(function () {
            kidCount++;
            if (kidWidth == 0) {
                kidWidth = $(this).outerWidth(true);
            }
            stageWidth += kidWidth;
        });
        Stage.width(stageWidth);

        // not enough kids to skim; done
        if (kidCount <= visCount) {
            return;
        }
        Next.removeClass('disable');
        Next.unbind('click').bind('click', function () {
            if ($(this).hasClass('disable')) {
                return false;
            }

            skimOffset++;

            if ((skimOffset+visCount) >= kidCount) {
                $(this).addClass('disable');
            }

            Stage.animate({'margin-left' : '-=' + kidWidth}, 500, 'swing' );
            theKids.removeClass('last');
            theKids.eq(skimOffset-1).addClass('last');
            theKids.eq(skimOffset+visCount-1).addClass('last');
            Prev.removeClass('disable');
            return false;
        });
        Prev.unbind('click').bind('click', function () {
            if ($(this).hasClass('disable')) {
                return false;
            }

            skimOffset--;

            if (skimOffset < 1) {
                $(this).addClass('disable');
            }

            Stage.animate({'margin-left' : '+=' + kidWidth}, 500, 'swing' );
            theKids.removeClass('last');
            theKids.eq(skimOffset-1).addClass('last');
            theKids.eq(skimOffset+visCount-1).addClass('last');
            Next.removeClass('disable');
            return false;
        });
    });
};

function show_konto_info(){
	var loc = window.location.hostname;
	if(loc.substr(0,10)=='www.btv.at'){
		window.location.href = 'http://www.btv.at/de/privatkunden/konten_und_karten/btv-kontopakete-id46.html#';
	}else{
		if(loc.substr(0,15)=='www.btv-bank.de'){
			window.location.href = 'http://www.btv-bank.de/de/privatkunden/konten_und_karten/btv-kontopakete-id46.html#';
		}else{
			if(loc.substr(0,13)=='btv.unitb.com'){
			 window.location.href = 'http://btv.unitb.com/de/privatkunden/konten_und_karten/';
			}
		}
	}
}
//
// Online-Rechner
//
function init_online_calculators()
{
    $('#sparen_ergebnis,#haushalt_ergebnis').hide();

    //
    // Sparrechner
    //
    $('#sparen_einmalzahlung_slider').slider({value:2500, min:0, max:100000, step:500, range:'min'})
        .bind('change slide', function (event, ui) {
            var val = parseInt(ui.value/500)*500;
            $('#sparen_einmalzahlung_display').val(number_format(val, 0, ',', '.')).attr('title', val);
            sparen_berechneZinsen();
        });

    $('#sparen_wiederkehr_slider').slider({value:0, min:0, max:1000, step:10, range:'min'})
        .bind('change slide', function (event, ui) {
            var val = parseInt(ui.value/10)*10;
            $('#sparen_wiederkehr_display').val(number_format(val, 0, ',', '.')).attr('title', val);
            sparen_berechneZinsen();
        });

    $('#sparen_anlagedauer_slider').slider({value:24, min:6, max:60, step:6, range:'min'})
        .bind('change slide', function (event, ui) {
            var val = parseInt(ui.value/6)*6;
            $('#sparen_anlagedauer_display').val(number_format(val, 0, ',', '.')).attr('title', val);
            sparen_berechneZinsen();
        });

    $('#sparen_zinssatz_slider').slider({value:2.5, min:0, max:5, step:0.125, range:'min'})
        .bind('change slide', function (event, ui) {
            var val = parseInt(ui.value/0.125)*0.125;
            $('#sparen_zinssatz_display').val(number_format(val, 3, ',', '.')).attr('title', val);
            sparen_berechneZinsen();
        });

    $('#sparen_einmalzahlung_display, #sparen_anlagedauer_display, #sparen_wiederkehr_display').bind('change', function () {
        var val = number_unformat($(this).val());
        var rutschi = $('#' + this.id.replace('_display', '_slider'));
        if (val > rutschi.slider('option', 'max')) {
            val = rutschi.slider('option', 'max');
        }
        if (val < rutschi.slider('option', 'min')) {
            val = rutschi.slider('option', 'min');
        }
        val = parseInt(val / rutschi.slider('option', 'step')) * rutschi.slider('option', 'step');

        $(this).val(number_format(val, 0, ',', '.')).attr('title', val);
        rutschi.slider('value', val);
        sparen_berechneZinsen();
    });
    $('#sparen_zinssatz_display').bind('change', function () {
        var val = number_unformat($(this).val());
        var rutschi = $('#' + this.id.replace('_display', '_slider'));
        if (val > rutschi.slider('option', 'max')) {
            val = rutschi.slider('option', 'max');
        }
        if (val < rutschi.slider('option', 'min')) {
            val = rutschi.slider('option', 'min');
        }
        val = parseInt(val / rutschi.slider('option', 'step')) * rutschi.slider('option', 'step');

        $(this).val(number_format(val, 3, ',', '.')).attr('title', val);
        rutschi.slider('value', val);
        sparen_berechneZinsen();
    });

    $('#sparen_recurrrence input').bind('change', function (event, ui) {
        sparen_berechneZinsen();
    })

    function sparen_berechneZinsen()
    {
        var K0 = $('#sparen_einmalzahlung_display').attr('title') * 1; // K null
        var K1;                                                        // K eins (Ergebnis)
        var SR = $('#sparen_wiederkehr_display').attr('title') * 1;    // Sparrate
        var SH = $('#sparen_recurrrence input:checked').val() * 1;     // Sparhäufigkeit
        var ZF = $('#sparen_zinssatz_display').attr('title') / 100;    // Zinsfuß (Zinssatz; in %)
        var nA = $('#sparen_anlagedauer_display').attr('title') * 1;   // n; Anzahl Perioden

        var dataX = ['0 Mon.'];
        var dataY = [K0*1];

        if (nA != 0) {
            for (var i = 6; i <= nA ; i += 6) {
                dataX.push(i + ' Mon.');
                K1 = 0;
                if (K0 > 0) {
                    K1 += K0 * Math.pow(1 + ZF, (i / 12) );
                }
                if (SR > 0) {
                    K1 += SR * ( (Math.pow(1 + (ZF / SH), (i / 12 * SH) )-1) / (ZF / SH) );
                }
                dataY.push(Math.round(K1 * 100) / 100);
            }
        }
        $('#sparen_ergebnis').show().find('#sparen_ergebnis_wert').text(number_format(K1, 2, ',', '.'))
        $('#sparen_legende').show();

        chart1 = new Highcharts.Chart({
            chart: { renderTo: 'sparen_graph', type : 'column', borderWidth: 1, borderColor: '#E5E5E5'},
            title: { text: null },
            xAxis: { categories: dataX  },
            yAxis: { title: { text: 'Kapital'}, min: 0},
            tooltip : {
                formatter: function() {
                    return '<b>' + this.series.name + '</b><br/>' + this.x + ': ' + number_format(this.y, 2, ',', '.') + '€';
                }
            },
            series: [{ name : 'Kapital', data: dataY }],
            credits: {enabled: false},
            legend :  { enabled: false, verticalAlign: 'bottom', align: 'left', layout: 'horizontal' }
        });
    }

    var kontokonfig_stepping = 100;
    //
    // Kontokonfigurator
    //
    $('#kontokonfig_disporahmen_slider').slider({value:2000, min:1600, max:12000, step:kontokonfig_stepping, range:'min'})
        .bind('change slide', function (event, ui) {
            var val = Math.floor(ui.value / kontokonfig_stepping) * kontokonfig_stepping;
            var displayVal = val <= 11000 ? number_format(val, 0, ',', '.') : 'mehr';
            $('#kontokonfig_disporahmen_display').val(displayVal).attr('title', kontokonfig_normalizeCardLimit(ui.value));
            kontokonfig_berechne();
        });

    $('#kontokonfig_inklusivkonten_slider').slider({value:1, min:1, max:5, step:1, range:'min'})
        .bind('change slide', function (event, ui) {
            var val = parseInt(ui.value);
            $('#kontokonfig_inklusivkonten_display').val(number_format(val, 0, ',', '.')).attr('title', val);
            kontokonfig_berechne();
        });

    $('#kontokonfig_inklusivkonten_display, #kontokonfig_disporahmen_display').bind('change', function () {
        var val = number_unformat($(this).val());
        var rutschi = $('#' + this.id.replace('_display', '_slider'));
        if ($(this).val() == 'mehr') {
            val = rutschi.slider('option', 'max');
        } else  if (val > rutschi.slider('option', 'max')) {
            val = rutschi.slider('option', 'max');
        } else  if (val < rutschi.slider('option', 'min')) {
            val = rutschi.slider('option', 'min');
        }
        val = parseInt(val / rutschi.slider('option', 'step')) * rutschi.slider('option', 'step');

        $(this).val(number_format(val, 0, ',', '.')).attr('title', val);
        if (this.id == 'kontokonfig_disporahmen_display') {
            var displayVal = val <= 11000 ? number_format(val, 0, ',', '.') : 'mehr';
            $(this).val(displayVal);
        }
        rutschi.slider('value', val);
        kontokonfig_berechne();
    });

    $('#kontokonfig_reiseversicherung input, #kontokonfig_milesnmore input').bind('change', function (event, ui) {
        kontokonfig_berechne();
    })

    function kontokonfig_normalizeCardLimit(value) {
        value = Math.floor(value / kontokonfig_stepping) * kontokonfig_stepping;
        return (value < 2200) ? 2000 : (value < 3000) ? 2200 : (value < 7500) ? 3000 : (value == 7500) ? 7500 : 12000;
    }

    function kontokonfig_berechne()
    {
        var Dispo  = $('#kontokonfig_disporahmen_display').attr('title') * 1;    // We need it numeric
        var Konten = $('#kontokonfig_inklusivkonten_display').attr('title') * 1; // We need it numeric
        var Versi = $('#kontokonfig_reiseversicherung input:checked').val();
        var Miles = $('#kontokonfig_milesnmore input:checked').val();

        var resultLayerId = null;

        switch (Konten) {
            case 1:
                switch (Dispo) {
                    case 2000:
                        switch (Miles) {
                            case "low":
                                switch (Versi) {
                                    case "low": resultLayerId = "#resultLayer_kompakt";       break;
                                    case "middle": resultLayerId = "#resultLayer_dynamik";    break;
                                    default: resultLayerId = "#resultLayer_prestige_familia";
                                }
                            break;
                            default: // Miles 'middle'
                                resultLayerId = "#resultLayer_prestige_familia";
                            break;
                        }
                    break;
                    case 2200: // Fall trough to 3000 ... it's still the same!
                    case 3000:
                        switch (Miles) {
                            case "low":
                                switch (Versi) {
                                    case "low": resultLayerId = "#resultLayer_dynamik";       break;
                                    case "middle": resultLayerId = "#resultLayer_dynamik";    break;
                                    default: resultLayerId = "#resultLayer_prestige_familia";
                                }
                            break;
                            default: // Miles 'middle'
                                resultLayerId = "#resultLayer_prestige_familia";
                            break;
                        }
                    break;
                    case 7500:
                        switch (Miles) {
                            case "low":
                                switch (Versi) {
                                    case "low": resultLayerId = "#resultLayer_dynamik";       break;
                                    case "middle": resultLayerId = "#resultLayer_dynamik";    break;
                                    default: resultLayerId = "#resultLayer_prestige_familia";
                                }
                            break;
                            default: // Miles 'middle'
                                resultLayerId = "#resultLayer_prestige_familia";
                            break;
                        }
                    break;
                    default: // Dispo > 7.500 € ...
                        resultLayerId = "#resultLayer_prestige_familia";
                    break;
                }
            break;
            default: // Konto > 1 ...
                resultLayerId = "#resultLayer_familia";
            break;
        }

        if ($('#kontokonfig_ergebnis ' + resultLayerId + ':visible').length < 1) {
            $('#kontokonfig_ergebnis .resultLayer').hide();
            $('#kontokonfig_ergebnis ' + resultLayerId).fadeIn(1000);
        }
    }



    //
    // Haushaltsrechner
    //
    $('#haushalt_in input, #haushalt_out input').keyup(function () {
        var income = 0, spendings = 0, result = 0, barIn = [], barOut = [], coloursIn = [], coloursOut = [];
        $('#haushalt_in input').each(function () {
            if ($(this).val().length > 0 &&  $(this).val() > 0) {
                income += $(this).val() * 1;
                barIn.push( {'name' : $(this).attr('title'), 'data' : $(this).val() * 1, 'type' : 'column' } );
                coloursIn.push('#9EBD56');
            }
        });
        $('#haushalt_out input').each(function () {
            if ($(this).val().length > 0 &&  $(this).val() > 0) {
                spendings += $(this).val() * 1;
                barOut.push( { 'name' : $(this).attr('title'), 'data' : $(this).val() * 1, 'type' : 'column' } );
                coloursOut.push('#8B0000');
            }
        });

        result = income - spendings;

        $('#haushalt_ergebnis').show().find('#haushalt_ergebnis_wert').text(number_format(result, 2, ',', '.') + '€');

        if (result > 0) {
            $('#haushalt_ergebnis').removeClass('minus');
        } else {
            $('#haushalt_ergebnis').addClass('minus');
        }

        if (barIn.length > 0) {
            chartIn = new Highcharts.Chart({
                chart: { renderTo: 'haushalt_graph_in', defaultSeriesType: 'column'},
                colors: coloursIn,
                title: { text: 'Einnahmen' },
                xAxis: { categories: ['Einnahmen'] },
                yAxis: { min: 0, max : (income > spendings ? income : spendings), title: { text: null }, stackLabels: { enabled: true, style: { fontWeight: 'bold', color: 'gray'} } },
                credits: { enabled: false },
                legend: { enabled: false },
                tooltip: { formatter: function() { return '<b>' + this.x + '</b><br/>' +  this.series.name + ': ' + this.y + '<br/>' + 'Total: ' + this.point.stackTotal; } },
                plotOptions: { column: { stacking: 'normal', dataLabels: { enabled: true, color: 'white' } } },
                series: barIn
            });
        }
        if (barOut.length > 0) {
            chartOut = new Highcharts.Chart({
                chart: { renderTo: 'haushalt_graph_out', defaultSeriesType: 'column'},
                colors: coloursOut,
                title: { text: 'Ausgaben' },
                xAxis: { categories: ['Ausgaben'] },
                yAxis: { min: 0, max : (income > spendings ? income : spendings), title: { text: null }, stackLabels: { enabled: true, style: { fontWeight: 'bold', color: 'gray'} } },
                credits: { enabled: false },
                legend: { enabled: false },
                tooltip: { formatter: function() { return '<b>' + this.x + '</b><br/>' +  this.series.name + ': ' + this.y + '<br/>' + 'Total: ' + this.point.stackTotal; } },
                plotOptions: { column: { stacking: 'normal', dataLabels: { enabled: true, color: 'white' } } },
                series: barOut
            });
        }
    });

    //
    // BIC/IBAN-Rechner
    //
    $('#biciban_losjetzt').bind('click', function(evt) {
        // Prevent bubbling of event
        evt.stopPropagation();
        evt.preventDefault();

        $('#biciban_fehlermeldung').hide();
        $('#biciban_ergebnis_container').hide();
        $('#biciban_ergebnis_kontoblz').hide();
        
        var BLZnachKTO = {'00' : '16000', '01' : '16000', '02' : '16000', '03' : '16000', '07' : '16000'
            ,'08' : '16000', '10' : '16000', '11' : '16000', '12' : '16000', '13' : '16000'
            ,'14' : '16000', '15' : '16000', '16' : '16000', '17' : '16000', '18' : '16000'
            ,'19' : '16000', '20' : '16000', '24' : '16000', '27' : '16300', '25' : '16000'
            ,'28' : '16300', '29' : '16300', '30' : '16300', '31' : '16310', '32' : '16320'
            ,'33' : '16330', '34' : '16340', '35' : '16350', '36' : '16360', '37' : '16370'
            ,'38' : '16380', '39' : '16390', '40' : '16400', '41' : '16410', '42' : '16420'
            ,'43' : '16430', '44' : '16440', '45' : '16450', '46' : '16460', '48' : '16000'
            ,'50' : '16000', '62' : '16000', '64' : '16000', '65' : '16000', '66' : '16000'
            ,'67' : '16340', '68' : '16430', '70' : '16400', '71' : '16310', '72' : '16320'
            ,'73' : '16420', '74' : '16430', '75' : '16360', '76' : '16320', '77' : '16460'
            ,'78' : '16370', '79' : '16000', '81' : '16310', '88' : '16000', '89' : '16000'
            ,'90' : '16000', '91' : '16000', '92' : '16000', '93' : '16320', '94' : '16330'
            ,'95' : '16000', '97' : '16000', '98' : '16000', '99' : '16000'
        };
        var kto_input = $('#biciban_kontonummer').val();
        var kto_land  = $('#biciban_land').val() == 'DE' ? 'DE' : 'AT';

        var ktonr = '', blz = '', iban = '', ibanzs = '', fiban = '', bic = '', bicn = '', bicland = '';
        var prf = '0';
        var rest = 0, pz = 0;
        
        ktonr = kto_input.replace(/[^0-9]/g, '');

        if (ktonr.length < 9 || ktonr.length > 11) {
            $('#biciban_fehlermeldung').text('Ungültige Kontonummer').show();
            return false;
        }
        
        ktonr = fillNull(ktonr, kto_land == 'DE' ? 10 : 11);
        // Algo je nach Land
        if (kto_land == 'DE') {
            var checkNr = ktonr;        
            if (checkNr.substr(0,2) == '00') {
                checkNr = checkNr.substr(2) + '00';
            }
            rest = ( checkNr.substr(0, 1)*2 + checkNr.substr(1, 1)*7 + checkNr.substr(2, 1)*6
                    + checkNr.substr(3, 1)*5 + checkNr.substr(4, 1)*4 + checkNr.substr(5, 1)*3
                    + checkNr.substr(6, 1)*2
                    ) % 11;
            if (rest == 0 || rest == 1) {
                pz = 0;
            }
            if (rest > 1) {
                pz = 11 - rest;
            }
            if (pz != checkNr.substr(7, 1)) {
                $('#biciban_fehlermeldung').text('Ungültige Kontonummer').show();
                return false;
            }
            bic = 'BTVADE61';
            bicn = 'BTVA DE 61';
            bicland = 'Deutschland';
        } else {            
            rest = ( ktonr.substr(0, 1)*5 + ktonr.substr(1, 1)*4 + ktonr.substr(2, 1)*3
                    + ktonr.substr(3, 1)*2 + ktonr.substr(4, 1)*7 + ktonr.substr(5, 1)*6
                    + ktonr.substr(6, 1)*5 + ktonr.substr(7, 1)*4 + ktonr.substr(8, 1)*3
                    + ktonr.substr(9, 1)*2
                    ) % 11;
            if (rest == 0) {
                pz = 0;
            }
            if (rest > 1) {
                pz = 11 - rest;
            }
            if (rest == 1 || (pz != ktonr.substr(10, 1)) ) {
                $('#biciban_fehlermeldung').text('Ungültige Kontonummer').show();
                return false;
            }
            bic = 'BTVAAT22';
            bicn = 'BTVA AT 22';
            bicland = 'Österreich';
        }

        blz = (kto_land == 'DE') ? '72012300' : BLZnachKTO[ktonr.substr(3, 2)];
        iban = getIBAN(kto_land, blz, ktonr);
        iban = intern(iban);
        ibanzs = extern(iban);
        
        $('#biciban_ergebnis_biciban').show();
        $('#biciban_ergebnis_container').show();
        $('#biciban_ergebnis_raw').text(iban);
        $('#biciban_ergebnis_nice').text(ibanzs);
        $('#biciban_ergebnis_bic').text(bic);
        $('#biciban_ergebnis_bic_nice').text(bicn);
        $('#biciban_ergebnis_bicland').text(bicland);
        
        return false;
    });
    $('#biciban_pruefmich').bind('click', function(evt) {
        // Prevent bubbling of event
        evt.stopPropagation();
        evt.preventDefault();

        $('#biciban_fehlermeldung').hide();
        $('#biciban_ergebnis_container').hide();
        $('#biciban_ergebnis_biciban').hide();
        $('#biciban_ergebnis_kontoblz').hide();
        
        var iban_input = $('#biciban_iban').val().toUpperCase(); // Evade problems with case
               
        iban = iban_input.replace(/[^0-9ADET]/g, '');

        if ((iban.substr(0, 2) == 'DE' && iban.length != 22) 
                || (iban.substr(0, 2) == 'AT' && iban.length != 20) ){
            $('#biciban_fehlermeldung').text('Ungültige IBAN').show();
            return false;
        }
        var checksum = CheckSumIBAN(iban.substr(0, 2) + '00' + iban.substr(4));        
        if (checksum != iban.substr(2, 2)) {
            $('#biciban_fehlermeldung').text('Ungültige IBAN').show();
            return false;
        }
        
        var blz = '', blzn = '', ktonr = '', ktonrn = '', blzland = '';
        if (iban.substr(0, 2) == 'DE') {
            blz = iban.substr(4, 8);
            blzn = extern(blz, 3);
            ktonr = iban.substr(12);
            ktonrn = (ktonr.length == 9) ? extern(ktonr, 3) : extern(ktonr, 4);            
            blzland = 'Deutschland';
        } else if (iban.substr(0, 2) == 'AT') {
            blz = iban.substr(4, 5);
            blzn = blz.substr(0, 2) + ' ' + blz.substr(2);
            ktonr = iban.substr(11);
            ktonrn = (ktonr.length == 9) ? extern(ktonr, 3) : extern(ktonr, 4);
            blzland = 'Österreich';
        } else {
            $('#biciban_fehlermeldung').text('Diese IBAN kann leider nicht geprüft werden').show();
            return false;
        }
        
        $('#biciban_ergebnis_kontoblz').show();
        $('#biciban_ergebnis_blz').text(blz);
        $('#biciban_ergebnis_blz_nice').text(blzn);
        $('#biciban_ergebnis_ktonr').text(ktonr);
        $('#biciban_ergebnis_ktonr_nice').text(ktonrn);
        $('#biciban_ergebnis_blzland').text(blzland);
        
        return false;
    });

    function fillNull(konto, laenge)
    {
        while (konto.length < laenge) {
            konto = '0' + konto;
        }
        return konto;
    }

    function getIBAN(land, blz, konto)
    {
        var fill_acc = getKonto(land, konto);
        var checksum = CheckSumIBAN(land + '00' + blz + fill_acc);
        return land + checksum + blz + fill_acc;
    }

    function CheckSumIBAN(iban)
    {
        var code = iban.substring(0, 2);
        var checksum = iban.substring(2, 4);
        var bban = iban.substring(4);
        var digits = '';
        for (var i = 0; i < bban.length; ++i) {
            var ch = bban.charAt(i);
            digits += ('0' <= ch && ch <= '9') ? ch : capital2digits(ch);
        }
        for (var i = 0; i < code.length; ++i) {
            var ch = code.charAt(i);
            digits += capital2digits(ch);
        }
        digits += checksum;
        checksum = 98 - doMod97(digits);
        return fillNull(checksum.toString(), 2);
    }

    function intern(extern)
    {
        return extern.replace(/\s/g, '');
    
        var s = '';
        for (var i = 0; i < extern.length; ++i) {
            if (extern.charAt(i) != " ") {
                s += extern.charAt(i);
            }
        }
        return s;
    }
    
    function extern(intern, steps)
    {
        if (typeof steps == 'undefined') {
            steps = 4;
        }
    
        var s = '';
        for (var i = 0; i < intern.length; i++) {
            if (i != 0 && i%steps == 0) {
                s += ' ';
            }
            s += intern.substr(i, 1);
        }
        return s;
    }

    function doMod97(digit_string)
    {
        var m = 0;
        for (var i = 0; i < digit_string.length; ++i) {
            m = (m * 10 + parseInt(digit_string.charAt(i))) % 97;
        }
        return m;
    }

    function getKonto(land, konto)
    {
        return fillNull(konto, land);
    }

    function capital2digits(ch)
    {
        var capitals = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for (var i = 0; i < capitals.length; ++i) {
            if (ch == capitals.charAt(i)) {
                break;
            }
        }
        return i + 10;
    }

}
//
// Online-Rechner - Ende
//



function number_format(number, decimals, dec_point, thousands_sep)
{
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function number_unformat(string)
{
    return string.replace(/\./g, '').replace(',', '.') * 1;
}


function rPosition(element, mouseX, mouseY)
{
    var offset = $(element).offset();
    var x = mouseX - offset.left;
    var y = mouseY - offset.top;

    return {'x': x, 'y': y};
}


var slideSwitchInterval = null;
var sliderCurrentPosition = -1;
var startSlider = true;


function slideSwitch(next)
{
    var start = false;
    var $active = $('.maxislider .overview li.active');

    if ($active.length === 0) {
        start = true;
        $active = $('.maxislider .overview li#startSlide');
    }

    var $next = next;
    if (!$next) {
        var $next =  $active.next().length ? $active.next() : $('.maxislider .overview li:first');
    }
    if ($(":hidden", $next).length > 0) {
        $('.maxislider .overview li').css({opacity: 0.0}).show();
    }
    
    sliderCurrentPosition = $('.maxislider .overview li').index($next);
    
    if (!$next.next().length) {
        $('.maxislider.fade .pager li a.next').addClass('disable');
    } else {
        $('.maxislider.fade .pager li a.next').removeClass('disable');
    }
    if ($next.index() > 0) {
        $('.maxislider.fade .pager li a.prev').removeClass('disable');
    } else {
        $('.maxislider.fade .pager li a.prev').addClass('disable');
    }
    // no fade on start
    if (startSlider) { 
        startSlider = false;
        $('.maxislider .overview li').css({opacity: 0}).show();
        $('.maxislider .overview li:first').css({opacity: 1});
         $next.addClass('active');
    }else {        
        $next.css({opacity: 0.3}).show();
        $active.animate({opacity: 0}, 100).hide();
        $active.addClass('last-active');    
        $next.addClass('active')
            .animate
                ({opacity: 1.0}
                , 1000
                , function() {
                    $active.removeClass('active last-active');
                    $($('.maxislider.fade .pager li a.pagenum').removeClass('active').get(sliderCurrentPosition)).addClass('active');
                    $('#toprowcontainer').removeClass('lighttext darktext');
                    if ($next.hasClass('lighttext')) {
                        $('#toprowcontainer').addClass('lighttext');
                    } else if ($next.hasClass('darktext')) {
                        $('#toprowcontainer').addClass('darktext');
                    }                               

                });

   }
    
}

function slideSwitchButton () {
    if (!$(this).hasClass('pagenum')) {
        var myPosition = $('.maxislider.fade .pager li a.pagenum.active').index('.maxislider.fade .pager li a.pagenum');
        if ($(this).hasClass('next')) {
            myPosition += 1;
        } else {
            myPosition -= 1;
        }
    } else {
        var myPosition = $('.maxislider.fade .pager li a.pagenum').index(this);
    }
    sliderStopInterval();
    slideSwitch($($('.maxislider .overview li').get(myPosition)));
    sliderStartInterval();
    return false;
}

function sliderStartInterval() {
    slideSwitchInterval = setInterval('slideSwitch()', sliderIntervalConfig || 8000);
}

function sliderStopInterval() {
    window.clearInterval(slideSwitchInterval);
    slideSwitchInterval = null;
}

(function( $ ) {
  $.fn.selects_text = function (options) {
       var settings = {'text_element':'.sternchentexte','text_elem':'.listingsbox','added_elem':null};
       var texte = {};
       jQuery.extend( settings , options );
       selects_text_setText( settings , texte);
       this.each( function () {
           jQuery(this).bind(
                'click select change',
                function () {
                    var  Item_class = jQuery.trim(jQuery('option:selected', this).attr('class'));
                    if (Item_class != null && Item_class != "") {
                        selects_text_drawText( this , settings, texte[Item_class]);
                        select_text_setHiddenField(settings, texte[Item_class]);
                    }
                }
           );
       });
       function selects_text_setText(settings, texte) {
           jQuery(settings.text_element).find('span').each(
                function () {
                    texte[jQuery.trim(jQuery(this).attr('class'))] = jQuery(this).text();
                }
           );
       }
       function select_text_setHiddenField(settings, text) {
           console.log("hidden fields: ", jQuery(settings.text_element).find('input[type=hidden]'));
           jQuery(settings.text_element).find('input[type=hidden]').val(text)
           console.log("hidden fields: ", jQuery(settings.text_element).find('input[type=hidden]'));
       }
       function selects_text_drawText( elem , settings ,text) {
           if (settings.added_elem == null) {
               settings.added_elem = jQuery('<p>').addClass('note');
               jQuery( elem ).after(settings.added_elem);
           }
           jQuery(settings.added_elem).empty();
           jQuery(settings.added_elem).text(text);
       }
  };
})( jQuery );




$(document).ready(function () {

    $('.tabbable').tabs();

    $('#kontopakete_accordion').accordion({'animated': 'size', autoHeight: false, active: false, collapsible: true });
    if (self.location.hash !== "") {
        $('#kontopakete_accordion').accordion('activate', self.location.hash);
    }

    $('#kreditsumme_slider').slider({value:2500, min:1000, max:500000, step:500, range:'min'})
        .bind('change slide', function (event, ui) {
            $('#kreditsumme_display').text(parseInt(ui.value/500)*500 );
        });

    $('#kreditlaufzeit_slider').slider({value:12, min:12, max:120, step:12, range:'min'})
        .bind('change slide', function (event, ui) {
            $('#kreditlaufzeit_display').text(parseInt(ui.value/12)*12 );
        });

    $('#mastermenu > li').bind('mouseenter', function () {
        if (flyOutActive !== true) {
            return true;
        }
        window.clearTimeout(masterFlyoutTO);
        $(this).addClass('focus');
        $('.flyout_menu:visible').stop(true, true).hide('fast').removeClass('focus');
        $('#topcountryselect ul, #toplangselect ul').hide();
        $(this).find('.flyout_menu').stop(true, true).show();
    }).bind('mouseleave', function () {
        masterFlyoutTO = window.setTimeout(closeFlyOut, 200);
        $(this).removeClass('focus');
    });

    $('.flyout_menu').bind('mouseenter', function () {
        window.clearTimeout(masterFlyoutTO);
        $(this).addClass('focus');
    }).bind('mouseleave', function () {
        $(this).removeClass('focus');
        closeFlyOut();
    });

    function closeFlyOut() {
        if ($('.flyout_menu.focus').length) {
            window.clearTimeout(masterFlyoutTO);
            return false;
        }
        if ($('#mastermenu > li.focus').length) {
            window.clearTimeout(masterFlyoutTO);
            return false;
        }
        $('.flyout_menu:visible').stop(true, true).hide();
    }

    $.fn.pilotTeaser = function(opts) {
        var options = $.extend({}, opts);

        return $(this).each(function() {
            var currentSelectedLevel1Value = null;
            var currentSelectedLevel2Value = null;

            var initialVisibleLevel2 = $('.semiselect.level2:visible');
            if (initialVisibleLevel2.length > 0) {
                currentSelectedLevel1Value = '#' + initialVisibleLevel2.attr('id')
            }

            $('.semiselect', this).bind('click', function () {
                $('.semiselect ul', this).hide(); // Hide all instances
                $(this).find('ul').show();
            });

            $('.semiselect ul li', this).bind('click', function (evt) {
                var newVal = $(this).text();
                var semSel = $(this).closest('.semiselect');

                semSel.find('div.text').text(newVal);
                $('ul', semSel).hide();

                if (semSel.hasClass('level1')) {
                    if (currentSelectedLevel1Value !== null) {
                        $(currentSelectedLevel1Value).hide();
                    }
                    currentSelectedLevel1Value = $(this).attr('data-value');
                    $(currentSelectedLevel1Value).show();
                } else if (semSel.hasClass('level2')) {
                    currentSelectedLevel2Value = $(this).attr('data-value');
                }

                evt.stopImmediatePropagation();
                evt.preventDefault();
                return false;
            });

            $('.container a.button', this).mousedown(function () {
                $(this).attr('href', currentSelectedLevel2Value);
                return true;
            });
            $('.container a.button', this).click(function () {
                if ($(this).attr('href') === '#') {
                    return false;
                } else {
                    return true;
                }
            });
        });
    }

    $.fn.searchFormAdvanced = function (opts) {
        var options = $.extend({}, opts);

        return $(this).each(
            function () {
                var that = this;
                var allCheckBox = $('input:checkbox[value=all]', this);
                var otherCheckBoxes = $('input:checkbox[value!=all]', this);
                if (allCheckBox[0].checked) {
                    otherCheckBoxes.each(
                        function (idx, checkBox) {
                            $(checkBox).attr('checked', 'checked').attr('disabled', 'disabled');
                        }
                    );
                }
                allCheckBox.click(
                    function (evnt) {
                        if (this.checked) {
                            otherCheckBoxes.each(
                                function (idx, checkBox) {
                                    $(checkBox).attr('checked', 'checked').attr('disabled', 'disabled');
                                }
                            );
                        } else {
                            otherCheckBoxes.each(
                                function (idx, checkBox) {
                                    $(checkBox).removeAttr('disabled');
                                    if (idx !== 0) {
                                        $(checkBox).removeAttr('checked')
                                    }
                                }
                            );
                        }
                    }
                );
            }
        );
    }
    $('.suchschlitz .suchoptionen').searchFormAdvanced();

    $('[placeholder]').defaultValue();

    $("body.search .numeric_pagination li a").click(
        function (evnt) {
            $form = $("body.search .suchschlitz form");
            $pageNumberField = $("input#pageNumber", $form);
            $pageNumberField.val(this.href.replace(/^[^#]*#(\d*)/, "$1"));
            $form.submit();
            return false;
        }
    );

    $(document).bind('mousemove', function() {
        flyOutActive = true;
        $(document).unbind('mousemove');
    })

    // fancybox configuration
    $('a.fb_iframe').fancybox({'width': '75%', 'height': '75%', 'autoScale': true, 'transitionIn': 'fade'
        ,'transitionOut': 'fade', 'speedIn': 600, 'speedOut': 200, 'overlayShow': true, 'type': 'iframe'
    });
    $('a.fb_video').fancybox({'titlePosition': 'inside', 'transitionIn' : 'none', 'transitionOut': 'none'});

    $('a.lightbox').each(attachLightbox);
    // Für inline eingebundene Galerien
    $('div.gs_widget').each(function() {
        var Me = $(this);
        gsWidget('#' + Me.attr('id'));
    });

    $('#topcountryselect, #toplangselect').click(function () {
        var menu = $(this).find('ul');
        if (menu.is(':visible')) {
            menu.hide();
        } else {
            $('#topcountryselect ul, #toplangselect ul').hide();
            menu.show();
        }
    });

    $('.article a.lightbox').each(function () {
        if ($(this).find('img').hasClass('right')) {
            $(this).addClass('right');
        }
        if ($(this).find('img').hasClass('top')) {
            $(this).addClass('top');
        }
        $(this).prepend('<div class="zoomin"></div>');
    });

    $('#menu_lotse_root input.lotse_selector, .lotse_selectable input.lotse_selector').live('click', function () {
        var myId = this.id;
        var myParent = $(this).parent().parent();
        var startLevel = null;

        if (myParent.hasClass('lotse_level_0')) {
            startLevel = 1;
            $('#lotseTeaserContainer').slideUp(500);
        } else {
            startLevel = myParent.hasClass('lotse_level_1') ? 2 : 3;
        }
        var incrLevel = startLevel
        while (incrLevel < 4) {
            $('.lotse_level_' + incrLevel).hide();
            incrLevel++;
        }

        var newMen = $('#' + myId.replace(/^rad\_/, 'menu_'));
        newMen.fadeIn(1000);
        if (newMen.find('input.lotse_selector').length) {
            newMen.find('input.lotse_selector:checked').trigger('click');
        }
        if ($('#menu_lotse_root input:checked').length > 0 && $('#lotseSecondLevel:visible').length === 0) {
            $('#lotseSecondLevel').slideDown(
                500,
                function () {
                    if ($('#lotseSecondLevel input:checked').length > 0 && $('#lotseTeaserContainer:visible').length === 0) {
                        $('#lotseTeaserContainer').slideDown(1500);
                    }
                }
            );
        } else {
            if ($('#lotseSecondLevel input:checked').length > 0 && $('#lotseTeaserContainer:visible').length === 0) {
                $('#lotseTeaserContainer').slideDown(1500);
            }
        }
    });

    $('#filialfinder_viewport area').click(function (e) {
        if (!filialFinderZoomed) {
            var rel = $(this).attr('rel');
            var coords = {'width' : 407, 'height' : 286, 'left' : 0, 'top' : 0};

            if (rel == 'germany') {
                coords = {'width' : 670, 'height' : 470, 'left' : 0, 'top' : 0};
            }
            if (rel == 'italy') {
                coords = {'width' : 650, 'height' : 456, 'left' : 0, 'top' : -169};
            }
            if (rel == 'suisse') {
                coords = {'width' : 1005, 'height' : 706, 'left' : 0, 'top' : -332};
            }
            if (rel == 'austria') {
                coords = {'width' : 606, 'height' : 425, 'left' : -200, 'top' : -64};
            }
            if (rel == 'tirol' || rel == 'innsbruck' || rel == 'kitzbuehel' || rel == 'osttirol') {
                coords = {'width' : 1160, 'height' : 814, 'left' : -159, 'top' : -371};
            }
            if (rel == 'vbg') {
                coords = {'width' : 1504, 'height' : 1056, 'left' : 0, 'top' : -481};
            }
            if (rel == 'vienna') {
                coords = {'width' : 1504, 'height' : 1056, 'left' : -1098, 'top' : -213};
            }

            $('#filialfinder_map')
                .animate(coords, 700).attr('usemap', '')
                .bind('click', function() { $('#filialfinder_back').click() });
            // AKR: #BTV-293: hide searchresult and clear searchfield before showing the list of filials of the map on click
            $(".suchschlitz .sucheingabe input.suchtext").val("");
            $(".searchResult").html("");
            // \#BTV-293
            $('#filialfinder_list_' + rel).show();
            $('#filialfinder_back').show();
            filialFinderZoomed = true;
        }
        e.stopImmediatePropagation();
        e.preventDefault();
        return false;
    });


    $('#filialfinder_back').click(function (e) {
        filialFinderZoomed = false;
        $('#filialfinder_back').hide();
        $('#filialfinder_map').unbind('click');
        $('.filialfinder_list').hide();
        $('#filialfinder_map').animate({'width' : 407, 'height' : 286, 'left' : 0, 'top' : 0}, 700).attr('usemap', '#filialfinder_map_coords');
    });

    // On the fly coordinate transformation
    $('#filialfinder_viewport area').each(function () {
        var factor = 407/1504;
        var coords = $(this).attr('coords').split(',');
        $.each(coords, function (k, v) {
            coords[k] = Math.round(v * factor);
        });
        $(this).attr('coords', coords.join(','));
    });

    var $maxislider = $('.maxislider');
    
    if ($maxislider.hasClass('fade')) {
        $("body .slidercontrols .pager li a, body.rubrik .maxislider.fade .pager li a").click( slideSwitchButton );
        slideSwitch($($('.maxislider .overview li').get(0)));
        $(".lightbox.gallery,.lightbox.video", $maxislider).click( sliderStopInterval );
        sliderStartInterval();
    } else {
        if (typeof sliderIntervalConfig == 'undefined') {
            sliderIntervalConfig = 0;
        }
    
        $maxislider.tinycarousel(
            {pager:true
            ,interval:true
            ,intervaltime : sliderIntervalConfig || 10000
            ,callback : function (element, index) {
                var Me = $(element);
                $('#toprowcontainer').removeClass('lighttext darktext');
                if (Me.hasClass('lighttext')) {
                    $('#toprowcontainer').addClass('lighttext');
                } else if (Me.hasClass('darktext')) {
                    $('#toprowcontainer').addClass('darktext');
                }
                
                try {
                   $('.lightbox.gallery,.lightbox.video', $maxislider ).click( function(){ setTimeout(function(){ $maxislider.tinycarousel_stop();},1000);  } );
                } catch (tinyCarouselException) {
                    /* ignore! */
                }
                
            }
        });
    }
    $('.teaserslider').teaserSlider();
    $('select').selects_text();
    
    $('.miniteaser .header ul li').each(function () {
        var tgt = $(this).find('a');
        if ($(this).hasClass('active')) {
            $(tgt.attr('href')).show();
        } else {
            $(tgt.attr('href')).hide();
        }        
        $(this).bind('click', function(evt) {
            $(this).addClass('active').siblings().removeClass('active');
            $(this).parent().find('li').each(function () {
                var tgt = $(this).find('a');
                if ($(this).hasClass('active')) {
                    $(tgt.attr('href')).show();
                } else {
                    $(tgt.attr('href')).hide();
                }
            });
            evt.stopImmediatePropagation();
            evt.preventDefault();
        });
    });
    
    $('form.newsletter').bind('submit', function (evt) {    
        try {
            var Me = $(this);        
            var emil = Me.find('input.email');
            var vorn = Me.find('input.vorname');
            var nach = Me.find('input.nachname');            
            var goOn = true;
            
            Me.find('input').removeClass('error');
            Me.find('div#formularfehler').hide();
            
            var emailRegex = /^(.+)\@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$/;
            var emailValue = emil.val();
            
            if (emailValue == '' || !emailRegex.test(emailValue)) {
                goOn = false;
                emil.addClass('error');
            }
            if (vorn.val() == '' || vorn.val() < 2) {
                goOn = false;
                vorn.addClass('error');
            }
            if (nach.val() == '' || nach.val() < 2) {
                goOn = false;
                nach.addClass('error');
            } 
            if (!goOn) {
                Me.find('div#formularfehler').show().text('Bitte füllen Sie die markierten Pflichtfelder aus');
                evt.preventDefault();
            }
            return goOn;            
        } catch (ex) {
            return true;
        }
    });    
});
