/*-- Spam protection --*/

    function getAdr(prefix, postfix, text){
        document.write('<a href="mailto:' + prefix + '@' + postfix + '">' + (text ? text.replace(/&quot;/g, '"').replace(/%EMAIL%/, prefix + '@' + postfix) : prefix + '@' + postfix) + '</a>');
    }

/* border-radius plugin */

    (function($){
        $.fn.borderRadius = function(radius){
            return this.each(function(e){
                $(this).css({
                    'border-radius': radius,
                    '-moz-border-radius': radius,
                    '-webkit-border-radius': radius
                });
            });
        };
    })(jQuery);

/*-- Iframe popup --*/

    (function($){
        $.fn.IframePopup = function(options){
            // Settings
            var IP_Settings = {
                margin: 20, // Margin from the iframe popup
                width: 700, // Default popup width
                height: 500, // Default popup height
                borderradius: '10px'  // Popup border-radius
            };
            var IP_Settings = $.extend(IP_Settings, options);
    
            // Create iframe popup
            createIframePopup();
            // Open iframe popup
            $(this).click(function(){
                // Hide scrollbar and fadein overlay
                $('body, html').css('overflow', 'hidden');
                $(ip_overlay).fadeTo('slow', 0.8);
                // Set tabindex="-1" to content
                $('a, input, textarea, select, button').not('.close').each(function(){
                    $(this).addClass('tabindex').attr('tabindex', '-1');
                });
                // Get popup size from rel attribut
                var popupHeight = this.rel.split(',')[1];
                var popupWidth = this.rel.split(',')[0];
                if(popupWidth == null || popupHeight == null){
                    popupWidth = IP_Settings.width;
                    popupHeight = IP_Settings.height;
                }
                // Set popup size
                var NormalCSS = {
                    'bottom': 'auto',
                    'height': popupHeight+'px',
                    'left': '50%',
                    'margin-left' : Math.floor(-(popupWidth)/2)+'px',
                    'margin-top': Math.floor(-(popupHeight)/2)+$(window).scrollTop()+'px',
                    'max-height': popupHeight+'px',
                    'top': '50%',
                    'width' : popupWidth+'px'
                };
                var FlexibleCSS = {
                    'bottom': IP_Settings.margin+'px',
                    'height': 'auto',
                    'margin-top': 0,
                    'top': IP_Settings.margin+'px'
                };
                // Normal iframe popup size
                $(ip_popup).css(NormalCSS).borderRadius(IP_Settings.borderradius).show();
                // Flexible iframe popup size
                $(window).resize(function(){
                    ($(this).height() <= ($(ip_popup).height()+2*IP_Settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);
                });
                ($(window).height() <= ($(ip_popup).height()+2*IP_Settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);
                // Insert iframe title
                $(ip_title).html(this.title);
                // Insert iframe content
                $(ip_popup).addClass('ip_loading');
                $(ip_iframe).attr('src', this); 
                // Preloader
                $(ip_iframe).css('visibility', 'hidden');
                $(ip_iframe).load(function(){
                    $(ip_popup).removeClass('ip_loading');
                    $(ip_iframe).css('visibility', 'visible');
                });
                $(document).bind('keydown', keyDown);
                return false;
            });
    
            // Close popup
            function closeIframePopup(){
                $('body').css('overflow', bodyOverflow);
                $('html').css('overflow', htmlOverflow);
                $('.ip_popup').hide();
                $('.ip_overlay').fadeOut('slow');
                $(window).unbind('resize');
                // Remove tabindex="-1"
                $('.tabindex').each(function(){
                    $(this).removeClass('tabindex').removeAttr('tabindex');
                });
            }
    
            // Keyboard events
            function keyDown(event){
                var code = event.keyCode;
                return ($.inArray(code, [27,88,67]) >= 0) ? closeIframePopup() : true;
            }
    
            // Create iframe popup
            function createIframePopup(){
                $('body').append(
                    ip_overlay = $('<div>').attr({ 'class': 'ip_overlay' }).hide().click(closeIframePopup),
                    ip_popup = $('<div class>').attr({ 'class': 'ip_popup' }).append(
                        ip_close = $('<a>').attr({ 'class': 'close', href: '#', title: close+' [ESC]' }).text(close).click(closeIframePopup),
                        ip_title = $('<h2>').attr({ 'class': 'title' }),
                        $('<div>').attr({ 'class': 'ip_content' }).append(
                            ip_iframe = $('<iframe>').attr({ 'src': '', frameborder: '0' })
                        )
                    ).hide()
                );
                $([
                    bodyOverflow = $('body').css('overflow'),
                    htmlOverflow = $('html').css('overflow')
                ])
            }
        };
    })(jQuery);

/*-- datepicker -- */

    (function($){
        $.fn.datePicker = function(options){
            // Plugin options
            var now = new Date();
            var defaults = {
                hideInput: false, // Hide the coresponding input
                month: now.getMonth(), // Start month
                year: now.getFullYear(), // Start year
                format: "d.m.y", // Date format
                disableWeekend: true, // Disable Sa/So clicks
                speed: 200 // in km/h 
            };
            var options = $.extend(defaults, options);
            var dp_count = 0;
            // Init plugin to each
            return this.each(function(){
                // Pass vars
                var op = options;
                var el = $(this);
                var mp = ( $(this).parent().is('label')) ? $(this).parent() : $(this); //mp as in mountpoint
                dp_count++;
                // Generate main .datepicker
                if(op.hideInput == true) el.hide();
                $('<div id="dp'+dp_count+'" class="datepicker"><h2>init</h2><a class="dpprev" href="#" title="'+back+'">'+back+'</a><a class="dpnext" href="#" title="'+next+'">'+next+'</a><table><thead><tr></tr></thead><tbody></tbody></table></div>').insertAfter(mp);
                var datepicker = $("#dp"+dp_count);
                $.each(days_list, function(index, value){ $("thead tr", datepicker).append('<th>'+value+'</th>') });
                //Measure fill
                for(t=0;t<=6;t++){ $("table", datepicker).append("<tr><td class='dpday dpclickable active'>19</td><td class='dpday dpclickable'>20</td><td class='dpday dpclickable'>21</td><td class='dpday dpclickable'>22</td><td class='dpday dpclickable'>23</td><td class='dpday'>24</td><td class='dpday'>25</td></tr>"); }  
                //CSS settings
                datepicker.css( { "width":$("table", datepicker).width()+"px","height":datepicker.height()+"px","overflow":"hidden" });
                // Fill init selected month
                fillDateTable( datepicker, el, op.month, op.year, op );
                // Generate the buttons
                $('a', datepicker).click(function(event){
                    event.preventDefault();
                    mont = jQuery.inArray($("h2 .dpmonth", datepicker).html(), mont_list);
                    year = $("h2 .dpyear", datepicker).html();
                    direction = $(this).hasClass("dpprev");
                    if( direction ) mont--;
                    else mont++;
                    if(mont>11){
                        mont = 0;
                        year++;
                    }
                    if(mont<0){
                        mont = 11;
                        year--;  
                    }
                    // Refill in selected direction
                    $("table", datepicker).stop(true, true).animate({marginLeft: (direction) ? '100%' : '-100%'}, op.speed, function(){
                        fillDateTable( datepicker, el, mont, year, op );
                        $("table", datepicker).css("marginLeft", (direction) ? '-100%' : '100%').animate({marginLeft:0}, op.speed);
                    });
                });
            });
            // Feed the .datepicker with data
            function fillDateTable(datepicker, el, mont, year, op){
                $("h2", datepicker).html('<span class="dpmonth">'+mont_list[mont] +'</span> <span class="dpyear">'+ year+'</span>');
                $("tbody tr", datepicker).remove();
                $("tbody", datepicker).append( generateMonthTable(mont, year));
                ncd = (op.disableWeekend == false) ? ":empty" : ":empty, .dpweekend";
                $('tbody td', datepicker).not(ncd).click(function(){
                    var format = op.format;
                    format = format.replace('m', ((jQuery.inArray($("h2 .dpmonth", datepicker).html(), mont_list))+1));
                    format = format.replace('d', $(this).html());
                    format = format.replace('y', $("h2 .dpyear", datepicker).html());
                    el.val(format);
                    $('tbody td.active', datepicker).removeClass("active");
                    $(this).addClass('active');
                    // remove error classes
                    el.parent().removeClass('error');
                    el.siblings('.error_msg').remove();
                });
            }
            // Generate the tbody
            function generateMonthTable(mont, year){
                var date = new Date(year, mont)
                var days = date.getDate();
                var firs = (date.getDay());
                if(firs == 0) firs = 7; // begin with Sundays
                var last = (new Date((new Date(year, mont+1,1))-1)).getDate();
                var now = new Date();
                var html = "<tr>";
                var d = 1;
                for(c=1;c<= Math.ceil(((last+(firs-1))/7))*7 ;c++){
                    var tdclass = ''; 
                    if(c>=firs && d<=last) tdclass += "dpday";
                    if(((c % 7 == 0) || ((c+1) % 7 == 0)) && d<=last) tdclass += " dpweekend";
                    if(!((c % 7 == 0) || ((c+1) % 7 == 0)) && c>=firs && d<=last ) tdclass += " dpclickable";
                    if(mont==now.getMonth() && year==now.getFullYear() && d==now.getDate()) tdclass += " dptoday";
                    html += "<td class='"+tdclass+"'>";
                    if(c>=firs&&d<=last) html += d++;
                    html += "</td>";
                    if (c % 7 == 0 && d<=last) html += "</tr><tr>";
                }
            return html + "</tr>";
            }
        };
    })(jQuery);

/*-- display elements --*/

    (function($){
        $.fn.showElement = function(options){
            var SE_Settings = {
                handler: 'toggle',
                destination: '',
                animate: false
            };
            var SE_Settings = $.extend(SE_Settings, options);
            // hide href anchor destination
            if($(this).length){             
                if($(this).is('a')){
                    var destination = ($(SE_Settings.destination).length) ? $(SE_Settings.destination) : $('#'+$(this).attr('href').split('#').pop());
                }
                else{
                    $(this).wrapInner('<a href="#" />');
                    var destination = $(SE_Settings.destination);
                }
                destination.hide();
                // show destination
                if(SE_Settings.handler == 'toggle'){
                    // toogle destination
                    $(this).toggle(
                        function(){ (SE_Settings.animate) ? destination.animate(SE_Settings.animate, { duration: 'slow' }) : destination.show(); },
                        function(){ (SE_Settings.animate) ? destination.animate(SE_Settings.animate, { duration: 'slow' }) : destination.hide(); }
                    );
                }
                else if(SE_Settings.handler == 'mouseover'){
                    // show destination on mouseover
                    $(this).bind({
                        click: function(){ return false; },
                        mouseover: function(){ (SE_Settings.animate) ? destination.animate(SE_Settings.animate, { duration: 'slow' }) : destination.show(); },
                        mouseout: function(){ (SE_Settings.animate) ? destination.animate(SE_Settings.animate, { duration: 'slow' }) : destination.hide(); }
                    });
                }
            }
        };
    })(jQuery);

/*-- anchor scroll --*/

    function initAnchorScroll(){
        $('a[href*="#"]').click(function(){
            var scroll = $(this).attr('href');
            if($(scroll).length){
                $('html, body').animate({
                    scrollTop: $(scroll).offset().top-10
                }, 600);
                return false;
            }
        });
    }

/*-- slideshow --*/

    var slideTimer;

    function initSlideshow(){
        var slideshow_margin_left = 293 * $('#slideshow .entry').length;
        var slideshow = slideshow_margin_left * 3;
        $('#slideshow .slide').css({
            'overflow': 'hidden',
            'width': slideshow,
            'margin-left': -slideshow_margin_left
        }).append(
            $('#slideshow .slide').html(),
            $('#slideshow .slide').html()
        );
        $('#slideshow').before(
            $('<div>').attr({ 'id': 'slideshow_nav' }).append(
                $('<a>').attr({ 'class': 'back', 'href': '', 'title': 'zurück' }).text('zurück').unbind().bind('click', function(){
                    var left = parseInt($('#slideshow .slide').css('margin-left'));
                    if(left == 0){
                        $('#slideshow .slide').css({
                            'margin-left': -slideshow_margin_left
                        });             
                    }
                    left = parseInt($('#slideshow .slide').css('margin-left'));
                    if(!$('#slideshow .slide').is(':animated')) {
                        $('#slideshow .slide').animate({
                            'margin-left': left + 293
                        }, 'slow');
                    }
                    return false;
                }),
                $('<a>').attr({ 'class': 'next', 'href': '', 'title': 'weiter' }).text('weiter').unbind().bind('click', function(){
                    var left = parseInt($('#slideshow .slide').css('margin-left'));
                    if(left <= -(slideshow-slideshow_margin_left)){
                        $('#slideshow .slide').css({
                            'margin-left': -slideshow_margin_left
                        });
                    }
                    left = parseInt($('#slideshow .slide').css('margin-left'));
                    if(!$('#slideshow .slide').is(':animated')){
                        $('#slideshow .slide').animate({
                            'margin-left': left - 293
                        }, 'slow')
                    }
                    return false;
                })
            )
        );
        $('#slideshow, #slideshow_nav a').hover(function(){
            if(slideTimer){
                window.clearInterval(slideTimer);
            }
        }, function(){
            slideTimer = window.setInterval("nextSlide()", 3000);
        });
        slideTimer = window.setInterval("nextSlide()", 3000);
    }

    function nextSlide(){
        $('#slideshow_nav a.next').click();
    }

/*-- news overview --*/

    function initNewsOverview(){
        var calendar = $('#news_calendar ul').find('li').length * 157;
        $('#news_calendar ul').css({
            'width': calendar
        });
        $('#news_calendar').css({
                'margin-left': 25,
                'overflow': 'hidden',
                'width': 466
            }).before(
            $('<div>').attr({ 'id': 'news_calendar_nav' }).append(
                $('<a>').attr({ 'class': 'back', 'href': '', 'title': 'zurück' }).text('zurück').unbind().bind('click', function(){
                    var left = parseInt($('#news_calendar ul').css('margin-left'));
                    if(left <= -157){
                        if(!$('#news_calendar ul').is(':animated')) {
                            $('#news_calendar ul').animate({
                                'margin-left': left + 157
                            }, 'slow');
                        }
                    }
                    return false;
                }),
                $('<a>').attr({ 'class': 'next', 'href': '', 'title': 'weiter' }).text('weiter').unbind().bind('click', function(){
                    var left = parseInt($('#news_calendar ul').css('margin-left'));
                    if((calendar-628) >= Math.abs(left)){
                        if(!$('#news_calendar ul').is(':animated')) {
                            $('#news_calendar ul').animate({
                                'margin-left': left - 157
                            }, 'slow')
                        }
                    }
                    return false;
                })
            )
        );
    };

/*-- jobs --*/

    (function($){
        $.fn.createJobsFilter = function(option){
            var options = new Array();
            var options_name = new Array();
            var options_value = new Array();
            var filter_head = $('.'+option, 'thead');
            var filter_body = $('.'+option, 'tbody');
            if($(filter_head).length){
                // Create select
                $(this).append(
                    $('<label>').attr({ 'for': 'filter_'+option }).text($(filter_head).text()),
                    filter_select = $('<select>').attr({ 'id': 'filter_'+option }).append(
                        $('<option>').attr({ 'value': '' }).text(show_all)
                    )
                );
                $(filter_body).each(function(){
                    var option = jQuery.trim($(this).text());
                    var create_new_option = 1;
                    for(var i=0; i<options.length; i++){
                        if(options[i] == option)
                            create_new_option = 0;
                    }
                    if(create_new_option){
                        options.push(jQuery.trim($(this).text()));
                        options_name.push(jQuery.trim($(this).text()));
                        options_value.push($(this).attr('class'));                  
                    }
                });
                options.sort();
                for(var i=0; i<options.length; i++){
                    var item_name = options[i];
                    var item_key = jQuery.inArray(item_name, options_name);
                    var item_value = options_value[item_key];       
                    $(filter_select).append(
                        $('<option>').attr({ 'value': item_value.split(' ')[1] }).text(item_name)
                    );
                }
            }
        };
    })(jQuery);

    (function($){
        $.fn.initJobsOverview = function(options){
            var JobsOverview_Settings = {
                position: true,
                location: true
            };
            var JobsOverview_Settings = $.extend(JobsOverview_Settings, options);
            var jobs_overview = $(this);
            if(jobs_overview.length){
                // Form
                if(JobsOverview_Settings['position'] == true || JobsOverview_Settings['location'] == true){
                    $('#jobs_overview').prepend(
                        form = $('<form>').attr({ 'action': '' })
                    );
                }
                // Position
                if(JobsOverview_Settings['position'] == true)
                    $(form).createJobsFilter('position');
                // Location
                if(JobsOverview_Settings['location'] == true)
                    $(form).createJobsFilter('location');
                // Filter on change
                $('select', form).change(function(){
                    var filter_value = new Array();
                    $('tbody tr', jobs_overview).show();
                    $('select', form).find('option:selected').each(function(){
                        filter_value.push(this.value);
                    });
                    $('tbody tr', jobs_overview).each(function(){
                        for(var i=0; i<filter_value.length; i++){
                            if(!$(this).children('td').hasClass(filter_value[i])){
                                $(this).hide();
                            }
                        }
                    });
                });
            }
        };
    })(jQuery);

/*-- Events --*/

    $.initEvents = function(){
        var events = '#events_overview';
        if(!$(events).length)
            return;

        $(events).prepend(
            form = $('<form action="">')
        );
        createFilter(form, 'category');
        if($(form).html().length){
            $('select', form).change(function(){
                var filter_value = new Array();
                $('tbody tr', events).show();
                $(this).find('option:selected').each(function(){
                    if(this.value.length)
                        filter_value.push(this.value);
                });
                $('tbody tr', events).each(function(){
                    for(var i=0; i<filter_value.length; i++){
                        if(!$(this).children('td').hasClass(filter_value[i]))
                            $(this).hide();
                    }
                });
            });
        }
        else{
            $(form).remove();
        }
        
        // Create filter
        function createFilter(form, option){
            var options_name = new Array(),
                options_value = new Array(),
                filter_head = 'thead .'+option,
                filter_body = 'tbody .'+option;
            if(!$(filter_head).length)
                return;
            // Create select
            $(form).append(
                filter_label = $('<label>').attr('for', 'filter_'+option).addClass('select').text($(filter_head).text()),
                filter_select = $('<select>').attr('id', 'filter_'+option).append(
                    $('<option value="">').text(show_all)
                )
            );
            $(filter_body).each(function(){
                var text = $.trim($(this).text()),
                    create_new_option = 1;
                if(text != '-'){
                    for(var i=0; i<options_name.length; i++){
                        if(options_name[i] == text)
                            create_new_option = 0;
                    }
                    if(create_new_option){
                        options_name.push(text);
                        options_value.push($(this).attr('class'));
                    }
                }
            });
            if(options_name.length > 1){
                options_name.sort();
                for(var i=0; i<options_name.length; i++){
                    var item_name = options_name[i],
                        item_value = options_value[$.inArray(item_name, options_name)];
                    $(filter_select).append(
                        $('<option>').attr('value', item_value.split(' ')[1]).text(item_name)
                    );
                }
            }
            else{
                $(filter_select).remove();
                $(filter_label).remove();
            }
        }
    };

/*-- startpage animation -- */

    function startpageAnimation() {
        if($('#animation').length) {
            $('#animation span').each(function() {
                $('<div>' + this.innerHTML + '</div>').hide().insertAfter($(this));
                $(this).hide();
            });
            // copy last child again
            var kids = $('#animation div');
            var lastkid = kids[kids.length-1];
            $('<div class="last">' + lastkid.innerHTML + '</div>').hide().insertAfter(lastkid);
            setTimeout('animateMe()', 500);
        }
    }

    var currentWord = -1;
    function animateMe() {
        var words = $('#animation span');
        var kids = $('#animation div');
        if(currentWord >= 0) {
            if(currentWord < words.length - 1) {
                $(kids[currentWord]).animate({
                    width: 0,
                    marginLeft: $(words[currentWord]).width()
                }, 800);
            }
            $(words[currentWord]).hide();
        }

        currentWord++;
        if(currentWord < words.length) {
            playSound(currentWord+1);
            var word = words[currentWord];
            var width = $(word).width();
            $(word).show();
            $(word).css({
                overflow: 'hidden',
                opacity: 0.8,
                width: 0,
                left: ((currentWord == words.length-1) ? (446) : (200 + 30*currentWord)) + 'px'
            });
            $(word).animate({
                width: width
            }, 1000);

            setTimeout('animateChild()', 500);
            setTimeout('animateMe()', 1700);
        }
        else {
            $(kids[currentWord-1]).animate({
                width: 0
            }, 800);
            $(kids[currentWord]).show().css({
                opacity: 0,
                left: 446 + 'px'
            });
            $(kids[currentWord]).animate({
                opacity: 1
            });
            playSound(currentWord+1);
        }
    }

    function animateChild() {
        var words = $('#animation div');
            var word = words[currentWord];
            var width = $(word).width();
            $(word).show();
            $(word).css({
                overflow: 'hidden',
                opacity: 1,
                width: 0,
                left: ((currentWord == words.length-2) ? (446) : (200 + 30*currentWord)) + 'px'
            });
            $(word).animate({
                width: width
            }, 1000);
    }

    function playSound(id) {
        // play sound
        var sounddiv = $('<div id="introsound' + id + '"></div>').hide().insertAfter($('#introsounds'));
        var flashvars = { soundid: id };
        var params = {};
        var attributes = {};
        //swfobject.embedSWF($('#introsounds')[0].href, "introsound"+id, "1", "1", "9.0.0", "", flashvars, params, attributes);
    }

/*-- clearfix ie -- */

    function clearfix(){
        // :after for IE
        if($.browser.msie && $.browser.version <= 8){
            $('.clearfix').each(function(){
                $(this).after(
                    $('<div>').css({
                        'clear': 'both',
                        'content': '" "',
                        'display': 'block',
                        'font-size': 0,
                        'height': 0,
                        'visibility': 'hidden'
                    })
                );
            });
        }   
    }

/*-- team -- */

    function initTeam(){
        // hide team entries without profil
        $('#team .entry').each(function(){
            var profil = $(this).children('.view_profil');
            if(!$(profil).length){
                $(this).hide();
            }
        })
        // append "Show all" button
        if($('#team .entry').length){
            $('#team').append(
                $('<div>').attr({
                    'class': 'show_all_team_entries'
                }).append(
                    $('<a>').attr({
                        'href': '#',
                        'title': 'Alle Ansprechpartner anzeigen'
                    }).text('Alle Ansprechpartner anzeigen').click(function(){
                        $('#team .entry').each(function(){
                            $(this).fadeIn('slow');
                        });
                        $(this).parent().remove();
                        return false;
                    })
                )
            );
        }
    }

/*-- appointmentmaker -- */

    function initApppointmentmaker(){
        $('.appointmentmaker').before(
            $('<div>').attr({
                'class': 'show_form'
            }).append(
                $('<a>').attr({
                    'href': '#',
                    'title': 'Termin vereinbaren'
                }).text('Termin vereinbaren').click(function(){
                    $('.appointmentmaker').fadeIn('slow');
                    $(this).parent().remove();
                    return false;
                })
            )
        ).hide();
    }

/*-- DOM -- */

    $(function(){
        // Forms
        $('form.contact').forms({ multipage: false, summarypage: true, error_value: false, progress_steps: false });
        $('form.appointmentmaker').forms({ multipage: false, summarypage: true, error_value: false, progress_steps: false });
        $('form.event').forms({ multipage: false, summarypage: true, error_value: false, progress_steps: false });
        $('#event_detail .register').removeClass('hideme');
        // Datepicker
        $('input.date').datePicker({ hideInput: true, format: "d.m.y" });
        $('.dpprev').borderRadius('3px');
        $('.dpnext').borderRadius('3px');
        // Show elements
        $('.show_disclaimer').showElement();
        // Iframe popup
        $('.popup').IframePopup();
        // Slideshow
        initSlideshow();
        // Clearfix
        clearfix();
        // Other pimps
        initAnchorScroll();
        initNewsOverview();
        $('#jobs_overview').initJobsOverview();
        initTeam();
        initApppointmentmaker();
        // Startpage animation
        startpageAnimation();
        $.initEvents();
    });

