jQuery(function($){
    var $this,
        $body = $('body'),
        $a    = $('a');

    // toggle links
    var $toggle_buttons = $a.filter('.toggle-button'),
        $toggle_content = $('div.toggle');

    $body.bind('click', function(){
        $toggle_content.removeClass('active');
    });
    $toggle_content.find('*').bind('click', function(event){
        event.stopPropagation();
    });
    $toggle_buttons.bind('click', function(event){
        event.preventDefault();
        event.stopPropagation();
        $this = $(this).parents('div.toggle:first');
        if ($this.is('.active')) {
            $this.removeClass('active');
        } else {
            $toggle_content.removeClass('active');
            $this.addClass('active');
        }
    });

    /**
     * Placeholder support for sucky browsers
     *
     * Browser does not support the placeholder attribute
     */
    if ( false === 'placeholder' in document.createElement('input') ) {
        // Find all the placeholders
        var placeHolderInputs = $('input[placeholder]');

        // Fallback support for jQuery's `.is(':focus')`, which is implemented
        // in version 1.6>
        // We're currently using version 1.5. It should be upgraded, but I don't
        // even dare to try!
        if ( typeof jQuery.expr[':'].focus === 'undefined' ) {
            jQuery.expr[':'].focus = function( elem ) {
                return elem === document.activeElement && ( elem.type || elem.href );
            };
        }

        placeHolderInputs.each( function () {
            var input = $(this),
                placeHolderText = input.attr('placeholder');

            // Store the placeholder data for each field for later use
            input.data('placeholder', placeHolderText);

            // Set the value attribute to equal the placeholder attribute if
            // the field is empty, and we're not focusing the element
            if (this.value === '' && false === input.is(':focus')) {
                this.value = placeHolderText;
            }
        });

        // Focus blur event handling
        placeHolderInputs.live('focus blur', function (e) {
            var elem = $(this),
                placeHolderText = elem.attr('placeholder');

            if (e.type === 'focusin') {
                // Field contains placeholder value, clear the field
                if (this.value === placeHolderText) {
                    this.value = '';
                } else {
                    elem.select();
                }
            } else {
                if (this.value === '') {
                    this.value = elem.attr('placeholder');
                }
            }
        });
    }

    // column more links: semantic trickery
    $a.filter('.button-banner').append('<span />');

    // main menu; hover
    $('ul').filter('.menu').find('> li:has(ul):not(.expanded)')
    .bind('mouseenter', function(){
        var $this = $(this).find('ul');
        $this.stop(true, true).show().animate({
            'top': '100%',
            'opacity': 1
        }, 200);
    })
    .bind('mouseleave', function(){
        var $this = $(this).find('ul');
        $this.stop(true, true).animate({
            'top': '0%',
            'opacity': 0
        }, 100, function() {
            $this.hide();
        });
    }).find('ul').css('opacity', 0);

    // main menu; margin
    var $header =  $('#content').find('> .header');
    if ( $header.is('.menu-expanded') ) {
        $header.css( 'margin-bottom', $header.find('> .menu > .expanded').find('> ul').outerHeight() + 'px' );
    }

    // slider
    var $slides,
        $pager,
        $pages,
        height = 0;
    $('div.slider').each(function(){
        var $this = $(this),
            $slides = $this.find('> div'),
            slides_count = $slides.length - 1,
            $pager = $this.find('ul.pager:first'),
            $pages = $('li a:not(.more)', $pager),
            _interval;

        $slides.each(function(){
            if ($(this).height() > height) {
                height = $(this).height();
                $this.height(height + 13);
            }
        }).filter(':not(:first)').hide();
        $pages.first().addClass('active');


        function start_interval() {
            _interval = setInterval(function(){
                var next_index = ( $slides.index($slides.filter(':visible').next()) );

                if ( next_index > slides_count  || next_index < 0 ) {
                    next_index = 0;
                }
                switch_slide( next_index );
            }, 5000);
        }
        document.body.onload = start_interval();

        function switch_slide( index ) {
            $slides.hide().eq( index ).show();
            $pages.filter('.active').removeClass('active');
            $pages.eq( index ).addClass('active');
        }

        $pages.bind('click', function(event){
            event.preventDefault();
            $this = $(this);
            if ($this.is('.active')) return false;

            clearInterval(_interval);
            switch_slide( $this.parent().index() );

        }).first().addClass('active');
    });


    // toopltip
    // plugin: jquery.tools.min.js
    $a.filter('.tooltip[href^=#]').each(function(){
        $this = $(this);
        $this.tooltip({
            delay:    45,
            position: 'bottom right',
            effect:   'slide',
            offset:   [15, -28],
            relative: true,
            tip:      '' + $this.attr('href') + ''
        });
    }).bind('click', function(event){
        event.preventDefault();
    });
    $a.filter('.tooltip:not([href^=#])').each(function(){
        $(this).tooltip({
            delay:    45,
            position: 'bottom right',
            effect:   'slide',
            layout:   '<div><span class="arrow" /></div>',
            offset:   [15, -34],
            tipClass: 'tooltip-content'
        });
    });

    // print: recipes
    var active_classes,
        multiple_recipes = false,
        $recipe_to_print;
    $('form.print-controls').bind('submit', function(event){
        event.preventDefault();
    }).find('a').bind('click', function(event){
        event.preventDefault();
        $this = $(this);
        
        //starts collecting html classes, whichll be used by the print css

        // 1: which parts of the recipe should be printed
        active_classes = $this.attr('href').replace('#', '');

        // 2: whether to exclude images
        if (!$this.siblings('label').find('input').is(':checked')) {
            active_classes += ' no-images';
        }

        // 3: if we are on a page with multiple recipes
        //    the one to be printed must be made targetable with css
        if ($this.parents('.food-tip').length > 0) {
            $recipe_to_print = $this.parents('.actions').parent('li').addClass('print-this');
            multiple_recipes = true;
        } else if ($this.parents('.recipe:not( #content )').length > 0) {
            $recipe_to_print = $this.parents('.recipe').addClass('print-this');
            multiple_recipes = true;
        } else if ($this.parents('.drink-recipe').length > 0) {
            $recipe_to_print = $this.parents('.drink-recipe').addClass('print-this');
            multiple_recipes = true;
        } else if ($this.parents('.drink_recipe').length > 0) {
            $recipe_to_print = $this.parents('.drink_recipe').addClass('print-this');
            multiple_recipes = true;
        }

        if (multiple_recipes) {
            active_classes += ' multiple-recipes';
        }

        // adds the collection of classes to body
        $body.addClass(active_classes);

        // prints
        // then removes the classes added above
        $(window).each(function(){
            this.print();
        }).each(function(){
            if (multiple_recipes) {
                $recipe_to_print.removeClass('print-this');
            }
            $body.removeClass(active_classes);
        });
    });

    // volume picker
    /*
    var $volume_selects = $('select').filter('.volume'),
        $volume_options,
        $prices;
    $volume_selects.each(function(){
        $this = $(this);
        $volume_options = $('option', $this);
        $prices = $this.next('strong.price').nextUntil('strong').hide();

        $($prices[$volume_options.index($this.find('option:selected'))]).show();

        $this.bind('change', function() {
            $($prices.hide()[$volume_options.index($this.find('option:selected'))]).show();
        } );
    });
    */

    // sort-by for folders
    var $sorter_forms = $('form.sorter');
    if ($sorter_forms.length > 0) {
        $sorter_forms.find('select').bind('change', function(){
            $(this).parents('form').submit();
        }).parents('form').show();
    }
    
    // price update for courses / giftcards
    var $courses_form = $('#courses');
    if ($courses_form.length > 0) {
        $courses_form.find('select.courses-giftcards').bind('change', function(){
            $(this).siblings('input[name="action"]').attr('name', 'giftcards');
            $(this).parents('form').submit();
        }).parents('form').show();
    }
    
    //backbutton functionality where there might be a module redirect involved
    $('#backbutton').click( function() {
        parent.history.back();
        return false;
    });

    // course giftcard preview
    $('form#courses input[type=submit]').click( function( e ) {
        if($(this).attr('id') == 'preview')
            $(this.form).attr('target', '_blank');
        else
            $(this.form).removeAttr('target');
    });

});

