﻿
// For easing
jQuery.easing.easeInOutQuad = function(x, t, b, c, d) {
    if ((t /= d / 2) < 1) return c / 2 * t * t + b;
    return -c / 2 * ((--t) * (t - 2) - 1) + b;
};

// Clear <input type="text" /> on focus
jQuery.fn.clearDefault = function(options) {
    settings = jQuery.extend({
        highlightClass: "highlight"
    }, options);
    return this.each(function() {
        jQuery(this).focus(function() {
            if (this.value == this.defaultValue)
                jQuery(this).attr("value", "").addClass(settings['highlightClass']);
        }).blur(function() {
            if (!this.value.length)
                jQuery(this).attr("value", this.defaultValue).removeClass(settings['highlightClass']);
        });
    });
};

// Split list elements for display purposes
jQuery.fn.splitList = function(cols, options) {
    settings = jQuery.extend({
        wrapClass: ""
    }, options);
    return this.each(function() {
        $lis = jQuery(this).find("> li");
        $inc = parseInt(($lis.length / cols) + ($lis.length % cols > 0));
        for (var i = 0; i < cols; i++)
            $lis.slice($inc * i, $inc * (i + 1)).wrapAll("<div class='" + settings['wrapClass'] + "'></div>");
    });
};

jQuery.fn.reverseChildren = function() {
    return this.each(function() {
        var parent = jQuery(this);
        jQuery(this).children().each(function() {
            jQuery(this).prependTo(parent);
        });
    });
}

var animating = false;
var is_video = false;

$(function() {

    if ($.browser.opera) $('input[type*="checkbox"],input[type*="radio"],select').css('background', '#FFF');

    if ($.browser.opera) $('body').addClass('opera');

    $('#campaigns').append('<a href="#" id="prev">previous</a><a href="#" id="next">next</a>');
    $('#scroller').append('<a href="#" class="prev">previous</a><a href="#" class="next">next</a>');
    $("#features ul").splitList(Math.ceil($("#features li").length / 2), { wrapClass: "row" });
    if ($.browser.msie && $.browser.version < 7)
        $('#scroller h3 a').css('behavior', 'url(../css/iepngfix.htc)');
    $("#scroller ul").splitList(3, { wrapClass: "slide" });
    $('#otherways ul:not(.featured)')
		.splitList(Math.ceil($("#otherways ul:not(.featured) li").length / 2), { wrapClass: "row" });
    $('#otherways .row li:nth-child(2)').addClass('right');

    $('#related-content .module:first').addClass('first');

    /* $("input[type=text]").clearDefault();   */
    $('#issue-browser')
		.splitList(2, { wrapClass: "wrap" })
		.find('.wrap:last-child')
		.addClass('wrap_last');
    $('#issue-browser li:not(#issue-browser ul li) > a').after(' <span class="opener"><a href="#">+</a></span>')
    $('#issue-browser > li > :not(ul), #issue-browser > div > li > :not(ul)')
	.css('cursor', 'pointer')
	.click(function(event) {
	    event.preventDefault();
	    var parent = $(this).closest('li');
	    if (parent.children('ul:visible').length == 0) {
	        $('#issue-browser > li, #issue-browser > div > li > ul:visible')
				.animate({ opacity: 'hide', height: 'hide' }, 200, 'easeInOutQuad')
				.end()
				.find('.opener a')
				.html('+');
	        parent
				.children('ul')
				.animate({ opacity: 'show', height: 'show' }, 200, 'easeInOutQuad')
				.end()
				.find('.opener a')
				.html('-');
	    } else {
	        parent
				.children('ul')
				.animate({ opacity: 'hide', height: 'hide' }, 200, 'easeInOutQuad')
				.end()
				.find('.opener a')
				.html('+');
	    }
	})

    $('#issue-browser > li > a, #issue-browser > li > .opener > a, #issue-browser > div > li > a, #issue-browser > div > li > .opener > a').hover(function() {
        if ($(this).parent().hasClass('opener')) $(this).toggleClass('hover').parent().siblings('a').toggleClass('hover');
        else $(this).toggleClass('hover').siblings('.opener').children('a').toggleClass('hover');
    }, function() {
        if ($(this).parent().hasClass('opener')) $(this).toggleClass('hover').parent().siblings('a').toggleClass('hover');
        else $(this).toggleClass('hover').siblings('.opener').children('a').toggleClass('hover');
    });

    // Add .last class for browsers that don't support :last-child
    $('#through-campaigns li:last,div:last-child,#site-nav ul ul a:last,#tools li:last-child,.pagination ul li:last-child,.item-list li:last-child').addClass('last');

    // Let ie css know that javascript is enabled
    $('body').removeClass('no-javascript').addClass('javascript');

    // Designers love adding >> to links. Here's how you do it without making screen reader users go crazy.
    $('#donate-form #othergive a,#moreabout a,.resources-promo a,.most li a,.animals #split ul a,#foot a:not(#foot_rss),.callout li a,a.more,#take-action #feature .more,#related-content h3 a,#related-content .more,.pagination .all,.pagination .next,#site-nav > li > ul > li > a,#event_detail #register .register a,#promo-takeaction a,.item-list .more a, .item-list .pdf a,#takeaction.expanded ul a,#issue-browser ul a,#resources li a,.links a,.simplepromo a')
		.wrapInner('<span></span>')
		.append('&nbsp;&raquo;')
		.addClass('raquo');
    $('.pagination .prev,.back,.crumb')
		.wrapInner('<span></span>')
		.prepend('&laquo;&nbsp;')
		.addClass('laquo');
    $('#billboard li .content li strong, #billboard li .video_content li strong')
		.wrapInner('<span></span>')
		.append('&nbsp;&gt;')
		.addClass('raquo');
    $('#sortby').hide();
    $('.list #top-pagination').append('<a href="#sortby"><span>Sort Page Listing</span>&nbsp;<span class="indic">+</span></a>');
    $('.search #top-pagination').append('<a href="#sortby"><span>Refine Search Results</span>&nbsp;<span class="indic">+</span></a>');
    $('#top-pagination a')
		.click(function(event) {
		    event.preventDefault();
		    if ($('#sortby:visible').length > 0) {
		        $('#top-pagination a .indic').html('+');
		        $('#sortby').animate({
		            'height': 'hide',
		            'opacity': 'hide'
		        }, 250, 'easeInOutQuad');

		    } else {
		        $('#top-pagination a .indic').html('-');
		        $('#sortby').animate({
		            'height': 'show',
		            'opacity': 'show'
		        }, 250, 'easeInOutQuad');
		    }
		});

    // Campaign scroller
    if ($('#campaigns ul').length > 0) {
        $('#campaigns ul').cycle({
            fx: 'scrollHorz',
            speed: 200,
            timeout: 0,
            next: '#next',
            prev: '#prev',
            easing: 'easeInOutQuad'
        });
    }


    if ($('#scroller ul').length > 0) {
        $('#scroller ul').cycle({
            fx: 'scrollHorz',
            speed: 250,
            timeout: 0,
            next: '#scroller .next',
            prev: '#scroller .prev',
            easing: 'easeInOutQuad',
            nowrap: 1,
            after: function(currSlideElement, nextSlideElement, options, forwardFlag) {
                var prevButton = $(this).parent().parent().find('.prev');
                var nextButton = $(this).parent().parent().find('.next');
                if ($(nextSlideElement).nextAll().length == 0)
                    nextButton.attr('id', 'disabled');
                else
                    nextButton.attr('id', '');
                if ($(nextSlideElement).prevAll().length == 0)
                    prevButton.attr('id', 'disabled');
                else
                    prevButton.attr('id', '');
            }
        });
    }

    // This block of code handles the homepage billboard
    if (!$.browser.msie || ($.browser.msie && $.browser.version >= 6)) {

        if (!$.browser.msie)
            $('.content *').css('opacity', 0.99);
        else if ($.browser.msie && $.browser.version >= 7)
            $('.content *').css('opacity', 0.99);

        // Initialize the billboard and pager
        var i = 1;
        var currentSlide = 1;
        var nextSlide;
        var animating = false;
        $('#billboard').reverseChildren();
        $('#home #head,.animals #head')
			.prepend('<ul id="pager"></ul>')
			.find('#billboard > li')
				.each(function() {
				    $(this).attr('id', 'slide-' + i)
				    $('#pager').append('<li><a href="#slide-' + i + '">' + i + '</a></li>');
				    ++i;
				});
        $('#billboard')
			.children()
				.addClass('slide')
				.css('opacity', 0)
				.end()
			.find('.content')
				.css('opacity', 0)
				.end()
		    .find('.video_content')
				.css('opacity', 0).css('display', 'none')
				.end()
			.find('> :first,> :first .content')
				.show()
				.css('opacity', 1)
				.end()
			.css('background-image', 'none');
        $('#pager a[href*="slide-1"]')
			.parent()
				.addClass('current');

        //this handles the video links
        $('#billboard .video_link a').click(function(e) {
            e.preventDefault();
            if (animating) return false;
            is_video = true;
            animating = true;
            $('#slide-' + currentSlide + ' .video_content_body .flash, #slide-' + currentSlide + ' .video_content_body .flash object').css({ 'visibility': 'hidden', 'display': 'none' });
            if ($.browser.msie && $.browser.version >= 8) {
                if (!!$('#slide-' + currentSlide + ' .video_content_body')[0].style)
                    $('#slide-' + currentSlide + ' .video_content_body')[0].style.removeAttribute('filter');
            }
            else
                $('#slide-' + currentSlide + ' .video_content_body').css('opacity', 1);
            $('#slide-' + currentSlide + ' .content').animate({ 'opacity': 0 }, 600, function() {
                $('#slide-' + currentSlide + ' .content').css('display', 'none');
                $('#slide-' + currentSlide + ' .video_content').css({ 'opacity': 0, 'display': 'block' })
                    .animate({ 'opacity': 1 }, 600, function() {
                        if ($.browser.msie && $.browser.version >= 8) {
                            if (!!$('#slide-' + currentSlide + ' .video_content_body')[0].style)
                                $('#slide-' + currentSlide + ' .video_content_body')[0].style.removeAttribute('filter');
                        }
                        //after transition is finished
                        var start = new Date().getTime();
                        for (var i = 0; i < 1e7; i++) {
                            if ((new Date().getTime() - start) > 300) {
                                break;
                            }
                        }
                        $('#slide-' + currentSlide + ' .video_content_body .flash, #slide-' + currentSlide + ' .video_content_body .flash object').css({ 'visibility': 'visible', 'display': 'block' });
                        animating = false;
                    });
            });
        });

        var autoAdvance = function() {
            if ($('#pager li.current').next().length > 0)
                $('#pager li.current').next().children('a').click();
            else
                $('#pager > li:first-child a').click();
        }
        var billboardInterval = setInterval(autoAdvance, 8000);
        $('#pager a, .video_link a').click(function(e) {
            // pageX is only defined on user clicks, not programmatic clicks
            if (e.pageX) window.clearInterval(billboardInterval);
        });

        // This is where the animation for the billboard is handled. Since it's 
        // comprised of several discrete steps, I had to use nested callbacks.

        var slideTransition = function(curSlide) {


            // At the same time as you're fading out the background of the current slide, fade in the background of the next slide
            $('#slide-' + nextSlide)
				.find('.content')
					.css({ 'opacity': 0, 'display': 'none' })
					.end()
				.css({ 'opacity': 0, 'display': 'block' })
				.animate({ 'opacity': 1 }, 600, function() {

				    // After the background of the next slide is done fading in, fade in the content of the next slide
				    $(this)
						.find('.content')
							.css({ 'opacity': 0, 'display': 'block' })
							.animate({ 'opacity': 1 }, 600, function() {
							    if (jQuery.browser.msie && $.browser.version >= 8) {
							        if (!!$(this).get(0).style)
							            $(this).get(0).style.removeAttribute('filter');
							    }
							    //    $(this).attr('style', 'display: block; zoom: 1;')
							    currentSlide = nextSlide;
							    if (jQuery.browser.msie) {
							        if (!!$('#slide-' + currentSlide + ' .content').get(0).style)
							            $('#slide-' + currentSlide + ' .content').get(0).style.removeAttribute('filter');
							        if ($('#slide-' + currentSlide + ' .video_content').length > 0)
							            if (!!$('#slide-' + currentSlide + ' .video_content').get(0).style)
							            $('#slide-' + currentSlide + ' .video_content').get(0).style.removeAttribute('filter');
							    }
							    nextSlide = null;
							    animating = false;
							});

				});
        }

        $('#pager a').click(function(event) {

            // Only procede if it's not currently animating
            if (!animating) {
                nextSlide = parseInt($(this).attr('href').charAt(($(this).attr('href').length - 1)));
                if (currentSlide != nextSlide) {
                    $('#pager li').removeClass('current');
                    $('#pager a[href*="slide-' + nextSlide + '"]').parent().addClass('current');
                    animating = true;
                    // if currently on video slide, hide it
                    if (is_video) {
                        is_video = false;
                        $('#slide-' + currentSlide + ' .video_content_body .flash, #slide-' + currentSlide + ' .video_content_body .flash object').css({ 'visibility': 'hidden', 'display': 'none' });
                        $('#slide-' + currentSlide + ' .video_content_body')
    					.animate({ 'opacity': 0 }, 300, function() {
    					    $('#slide-' + currentSlide + ' .content')
        				        .css({ 'opacity': 0, 'display': 'none' })
        				        .parent().animate({ 'opacity': 0 }, 600, function() {
        				            $(this).hide();
        				        });
    					    $('#slide-' + currentSlide + ' .video_content')
            					.animate({ 'opacity': 0 }, 600, function() {
            					    $(this).css('display', 'none');
            					});
    					    slideTransition($('#slide-' + currentSlide + ' .video_content'));
    					});
                    } else {
                        //else hide normal content
                        $('#slide-' + currentSlide)
    						.find('.content')
    						.animate({ 'opacity': 0 }, 300, function() {
    						    // Next, fade out the background of the current slide
    						    $(this)
                    				.hide()
                    				.parent()
                    				.animate({ 'opacity': 0 }, 600, function() {
                    				    $(this).hide();
                    				});
    						    slideTransition(this);
    						});
                    }
                }

            }
            event.preventDefault();

        });
    }


    // One-time donation form behavior
    /*
    $('#onetime-other')
    .change( function(){
    if( $(this).val() != "" ){
    $('input[name="onetime"]').attr('checked',false);
    }
    })
    .keypress( function(e){
    if (e.which > 31 && (e.which < 48 || e.which > 57))
    return false;
    return true;
    });
    $('input[name="onetime"]').change( function(){
    if( $('input[name="onetime"][checked="true"]').length > 0 ){
    $('#onetime-other').attr('value','');
    }
    });
    */

    // Monthly donation form behavior
    /*
    $('#monthly-other')
    .change( function(){
    if( $(this).val() != "" ){
    $('input[name="monthly"]').attr('checked',false);
    }
    })
    .keypress( function(e){
    if (e.which > 31 && (e.which < 48 || e.which > 57))
    return false;
    return true;
    });
    $('input[name="monthly"]').change( function(){
    if( $('input[name="monthly"][checked="true"]').length > 0 ){
    $('#monthly-other').attr('value','');
    }
    });
    */

    // Monthly donation form behavior
    /*
    $('#give-other')
    .change( function(){
    if( $(this).val() != "" ){
    $(this).val( Math.round( $(this).val().replace(/[^0-9\.]/g,'') ) );
    $('input[name="amount"]').attr('checked',false);
    $('.onetime-amt').html( parseInt( $(this).val() ) );
    $('.monthly-amt').html( Math.round( parseInt( $(this).val() / 6 ) ) );
    }
    });
    $('input[name*="amount"]').click( function(){
    $('#give-other').attr('value','');
    $('.onetime-amt').html( $(this).filter(':checked').val() );
    $('.monthly-amt').html( ($(this).filter(':checked').val()/6).toFixed(0) );
    $(this).blur();
    });
    */

    // Article image scroller
    if ($('#images').find('li').length > 1) {
        $('#images ul')
			.addClass('multiple')
			.before('<a class="prev" href="#">Previous</a> <a class="next" href="#">Next</a>')
			.cycle({
			    fx: 'scrollHorz',
			    speed: 200,
			    timeout: 0,
			    next: '#images .next',
			    prev: '#images .prev',
			    easing: 'easeInOutQuad'
			});
    }

    $('#features .row:last').css('background', 'none');

    /* Popups for news items */
    if (($.browser.msie == false && $.browser.opera == false) || ($.browser.msie && $.browser.version > 8)) {
        $('.popups .area-news .excerpt').hide();
        $('.popups .area-news li').each(function() {
            var popupHtml = '<div class="popup"><div class="header">';
            if ($(this).children('.date').length > 0)
                popupHtml += '<p class="date">' + $(this).children('.date').html() + '</p>';
            if ($(this).children('h3').length > 0)
                popupHtml += '<h3>' + $(this).children('h3').html() + '</h3>';
            popupHtml += '</div><div class="content">';
            if ($(this).children('.excerpt').length > 0)
                popupHtml += '<p>' + $(this).children('.excerpt').html() + '</p>';
            if ($(this).children('h3').children('a').length > 0)
                popupHtml += '<a class="more" href="' + $(this).children('h3').children('a').attr('href') + '">Read&nbsp;More</a>';
            popupHtml += '</div></div>';
            $(this).append(popupHtml).children('.popup').hide().hover(null, function(event) {
                animating = true;
                $(this).animate({
                    'top': (parseInt($(this).css('top')) - 10) + 'px',
                    'opacity': 0
                }, 1, 'easeInOutQuad', function() {
                    $(this).hide();
                    animating = false;
                });
                $(this).siblings('h3').children('a').css('text-decoration', 'none');
            });
        });
        $('.popup .more,.popup .action')
			.wrapInner('<span></span>')
			.append('&nbsp;&raquo;')
			.addClass('raquo');
        $('.popups .area-news li > h3 a').hover(function(event) {
            if (animating == false) {
                animating = true;
                $(this).css('text-decoration', 'underline');
                var popup = $(this).parent().siblings('.popup');
                var parent = $(this).parent().parent('li');
                var topPos = (event.pageY - parent.offset().top - popup.height() + parseInt(popup.css('padding-top')) + parseInt(popup.css('padding-bottom')) - 16) + 'px';
                var leftPos = (event.pageX - parent.offset().left - ((parseInt(popup.css('width')) + parseInt(popup.css('padding-left')) + parseInt(popup.css('padding-right'))) / 2)) + 'px';
                popup.show().css({
                    'top': topPos,
                    'left': leftPos,
                    'opacity': 0
                }).animate({
                    'top': (parseInt(popup.css('top')) - 10) + 'px',
                    'opacity': 1
                }, 1, 'easeInOutQuad', function() {
                    animating = false;
                });
            }
        });
    }

    if ($.browser.msie) {
        $('label > img').click(function() {
            $(this).parent().click();
        });
    }

});


