$(window).load(function(){
    var header = $('#header'),
        header_right = $('> .right', header),
        ticker = $('#news-ticker', header),
        body = $('body'),
        content = $('#content'),
        share = $('> .share', header_right),
        slideshow = $('#slideshow');
    // {{{ text size changer
    var smaller = $('<a href="#">Smaller</a>').click(function(e){
        e.preventDefault();
        var font_size = body.css('font-size');
        font_size = parseInt(font_size) - 1;
        if (font_size < 1)
        {
            font_size = 1;
        }
        body.css('font-size', font_size + 'px');
    });
    var larger = $('<a href="#">Larger</a>').click(function(e){
        e.preventDefault();
        var font_size = body.css('font-size');
        font_size = parseInt(font_size) + 1;
        body.css('font-size', font_size + 'px');
    });
    var text_changer = $('<div class="text-changer">Text: </div>')
        .append(smaller)
        .append(' | ')
        .append(larger);
    // $('> .site-search', header_right).after(text_changer);
    $('#board-link').before(
        text_changer
            .clone(true)
            .removeClass('text-changer')
            .append(' | ')
            .css({
                'display': 'inline'
            })
    );

    // }}}
    // {{{ flyout menus
    $('.flyout-menu').each(function(){
        var el = $(this),
            prev = el.prev(),
            prev_width = prev.width(),
            li = el.parent(),
            bg_image = prev.hasClass('selected') 
                ? '/images/arrow-right-gold.png' 
                : '/images/arrow-right-grey.png',
            position = prev.position(),
            li_offset = '4px';
        if ($.browser.safari)
        {
            li_offset = '3px';
        }
        else if ($.browser.msie)
        {
            li_offset = '5px';
        }
        li.css({
            'position' : 'relative',
            'background' : 'transparent url(' + bg_image + ') no-repeat scroll ' + (prev_width + 2) + 'px ' + li_offset
        });
        el.css({
            'background-color' : '#F1EBDA',
            'left' : 18 + prev_width + 'px',
            'top' : -1 - parseInt(el.css('padding-top')) + 'px'
        });
        li.hover(
            function(){
                el.show();
                prev.css('color', '#A17D0A');
                li.css(
                {
                    'background-image' : 'url(/images/arrow-right-gold.png)',
                    'z-index' : '100'
                });
            },
            function(){
                el.hide();
                li.css('z-index', '0');
                if (!prev.hasClass('selected'))
                {
                    prev.css('color', '#4A4A4A');
                    li.css('background-image', 'url(/images/arrow-right-grey.png)');
                }
            }
        );
    });
    
    // }}}
    // {{{ date field
    if (location.pathname == '/press-room/news-archive/')
    {
        $('form .field input.date').datepicker({
            dateFormat: 'yy-mm-dd',
            prevText: '&laquo;',
            nextText: '&raquo;'
        });
    }
    
    // }}}
    // {{{ related links more
    $('.col2 > ul', content).each(function(){
        var el = $(this),
            more = $('<div class="more"><a>open...</a></div>'),
            ul_height = el.height(),
            ul_margin_bottom = el.css('margin-bottom'),
            li_height = 16,
            num_li = el.children('li').length,
            num_show = el.hasClass('related-programs') || el.hasClass('program-locations') ? 5 : 4,
            new_margin_bottom = '0px',
            new_height = (li_height * (num_show)) - 7 + 'px';

        if (el.hasClass('missed-a-newsletter'))
        {
            return false;
        }
        if (el.hasClass('recent-publications') 
            || el.hasClass('recent-news') 
            || el.hasClass('learn-about-donating'))
            {
                $('> li:last', el)
                    .prev()
                    .css('margin-bottom', '0px');
                return true;
            }
        more
            .data('open', false)
            .click(function(e){
                e.preventDefault();
                more
                    .prev('ul')
                    .animate({ 
                        height: more.data('open') ? new_height : ul_height,
                        paddingBottom: more.data('open') ? '4px' : '0px'
                    }, 'normal', 'linear', function(){
                        more.data('open', !more.data('open'));
                        var action = more.data('open') ? 'close...' : 'open...';
                        $('> a', more).text(action);
                    });
            });

        if (num_li > num_show)
        {
            el
            .css({
                'height' : new_height,
                'margin-bottom' : new_margin_bottom,
                'padding-bottom' : '4px'
            })
            .after(more);
        }
    });
    
    // }}}
    // {{{ slideshow
    if (slideshow.length)
    {
        slideshow.show();
        // {{{ convert slideshow list to div slides
        $('> li', slideshow).each(function(i){
            var el = $(this),
                img = $('> img', el),
                frame = $('<li class="slide"></li>'),
                caption = $('<p class="caption"></p>');
            el.remove();
            if (img.length)
            {
                caption
                    .text(el.text());
                frame
                    .hide()
                    .css('background-image', 'url(' + img.attr('src') + ')')
                    .append(caption);
                if (i === 0)
                {
                    frame.fadeIn();
                }
                slideshow
                    .append(frame);
            }
        });

        // }}}
        // {{{ controls
        var slide_controls = $('<div class="controls"></div>'),
            slide_pause = $('<div class="pause"></div>'),
            slide_play = $('<div class="play"></div>'),
            slide_prev = $('<div class="prev"></div>'),
            slide_next = $('<div class="next"></div>');
        slide_pause
            .text('Pause')
            .click(function(){
                clearInterval(slide_int);
            });
        slide_play
            .text('Play')
            .click(function(){
                slide_int = setInterval("start_show('next')", 6000);
            });
        slide_prev
            .text('Previous')
            .click(function(){
                clearInterval(slide_int);
                if (slideshow.data('enable'))
                {
                    start_show('prev');
                }
            });
        slide_next
            .text('Next')
            .click(function(){
                clearInterval(slide_int);
                if (slideshow.data('enable'))
                {
                    start_show('next');
                }
            });
        slide_controls
            .append(slide_prev)
            .append(slide_next);
        slideshow
            .data('enable', true)
            .append(slide_controls);

        // }}}
        slide_play.click();
    }

    // }}}
    //{{{ introduce a friend
    var iaf = $('#introduce-a-friend');
    if (iaf.length > 0)
    {
        var iaf_add = $('<a>Add More Friends</a>')
                        .click(function() {
                            var friend = $('> li:first', iaf).clone();
                            $('input', friend).val('');
                            iaf.append(friend)
                                .append(friend.clone());
                        });
        iaf.after(iaf_add);
    }
    //}}}
    // {{{ textarea msg limit
    $("textarea[name='contact[comments]']")
        .keydown(function(e){
            switch (e.which)
            {
                case 0:
                case 8:
                case 17:
                case 18:
                case 224:
                    $(this).data('stop', false);
            }
        })
        .keypress(function(e){
            var el = $(this);
            if (el.data('stop'))
            {
                return false;
            }
        })
        .keyup(function(e){
            var el = $(this),
                val = el.val();
            if (val.length >= 255)
            {
                el.data('stop', true).val(val.substr(0,255));
            }
            else
            {
                el.data('stop', false);
            }
        });
    // }}}
    // {{{ newsletter archives
    $("#newsletter-archives")
        .change(function(e){
            var url = $(':selected', this).val();
            if (url.length)
            {
                window.open(url, '_blank');
            }
        });
    // }}}
    if (ticker.length)
    {
        start_ticker(true);
    }
    setTimeout("next_slide('#banner', 7000)", 7000);
    $('a.lang', content)
        .attr('href', '')
        .click(function(e){
            e.preventDefault();
            $.get('/service/language/', { skip : 1 }, function(data) {
                location.reload(true);
            });
        });
});

// {{{ function next_slide(selector, time)
function next_slide(selector, time)
{
    var banner = $(selector),
        slides = $(' > .slide', banner),
        n = slides.length,
        speed = 2000;
    if (n < 2)
    {
        return false;
    }
    slides.each(function(i){
        var el = $(this);
        if (!el.hasClass('hidden'))
        {
            var next_slide = i === n-1 ? slides.eq(0) : el.next();
            el.fadeOut(speed, function(){ 
                $(this).addClass('hidden') 
            })
            next_slide.fadeIn(speed, function(){ 
                $(this).removeClass('hidden') 
            });
            setTimeout("next_slide('" + selector + "', '" + time + "')", time);
        }
    });
}
// }}}
// {{{ function start_show(control)
function start_show(control)
{
    var slideshow = $('#slideshow'),
        slides = $('> .slide', slideshow),
        slides_length = slides.length;
    slideshow.data('enable', false);
    slides.each(function(i){
        var el = $(this);
        if (el.css('display') !== 'none')
        {
            el.fadeOut('slow');
            if (i === slides_length-1 && control !== 'prev')
            {
                slides.eq(0).fadeIn('slow', function(){ slideshow.data('enable', true) });
            }
            else
            {
                if (control === 'prev')
                {
                    if (i === 0)
                    {
                        slides.eq(slides_length-1).fadeIn('slow', function(){ slideshow.data('enable', true) });
                    }
                    else
                    {
                        el.prev().fadeIn('slow', function(){ slideshow.data('enable', true) });
                    }
                }
                else
                {
                    el.next().fadeIn('slow', function(){ slideshow.data('enable', true) });
                }
            }
            return false;
        }
    });
}

// }}}
// {{{ function start_ticker(first_run)
function start_ticker(first_run)
{
    var ticker_width = 470,
        ticker_slide_width = ticker_width + 50,
        ticker = $('#news-ticker'),
        ticker_slides = $('> .slide', ticker),
        slide_length = 20000;
    if (first_run)
    {
        $('#ticker-container')
            .css('width', ticker_width + 'px');
        ticker
            .css('width', ticker_width + 'px');
        ticker_slides
            .css({
                'width' : ticker_slide_width + 'px',
                'left' : ticker_slide_width + 'px'
            });
    }

    setTimeout('start_ticker(false)', slide_length/1.5);
    ticker_slides.each(function(){
        var el = $(this);
        if (el.css('left') === ticker_slide_width + 'px')
        {
            el
            .animate({
                left: '-' + ticker_slide_width + 'px'
            }, slide_length, 'linear', function(){
                el
                .appendTo(ticker)
                .css('left', ticker_slide_width + 'px');
            });
            return false;
        }
    });
}

// }}}

