var ytPlayer;
function onYouTubePlayerReady(playerId) {
    ytPlayer = document.getElementById('ytplayer');
}

jQuery(document).ready(function($) {

    // fade out error message bg color
    $("#messages, #comment_errors, #comment_msgs").animate({opacity: 1.0}, 3000).animate({backgroundColor: '#ffffff'}, 3000);


    // share bookmarks on thankyou pages
    vanilla.baseUrl = location.href.split('?', 1);
    $(".thankyoubookmarks").bookmark({
        icons: "/images/bookmarks.png",
        url: vanilla.baseUrl,
        sites: ["delicious", "digg", "facebook", "fark", "google", "mixx", "propeller", "reddit", "stumbleupon", "technorati", "twitthis", "yahoobuzz"]
    });
    $(".thankyoubookmarks").prepend('<p><strong>Share this with your friends:</strong></p>');
    
    // share bookmarks in general
    $(".bookmarks").bookmark({
        icons: "/images/bookmarks.png", 
        sites: ["delicious", "digg", "fark", "google", "mixx", "propeller", "reddit", "stumbleupon", "technorati", "yahoobuzz"]
    });
    
    // share bookmarks popup
    $('#tools ul li.share a.top_a').click(function() {
        if ($('#tools .share_wrapper').css('left') == '-8888px') {
            $('#tools .share_wrapper').css('left', 0);
        } else {
            $('#tools .share_wrapper').css('left', '-8888px');
        }
        return false;
    });


    //  hide or show field -- pledge vs donation

		
		 $('input.donation').click(function() { 
		    $('.formrow_existing_pledge_acct').hide('slow');
		    return true;
		  });
		
		  $('input.pledge').click(function() {
		    $('.formrow_existing_pledge_acct').show('slow');
		    return true;
		  });


    // opacity effect for bookmarks
    $(".hasBookmark ul a").css("opacity", ".6");
    $(".hasBookmark ul a").hover(
        function() {
            $(this).css("opacity", "1");
        },
        function() {
            $(this).css("opacity", ".6");
        }
    );

    // homepage slideshow 

    $('#home_features .listeditem').wrapAll('<div id="fade" />');
	$('#fade').css('background', '#000');

    // design feature controls
	var featureCt = $('#fade .listeditem').length;
    $('#home_features').each(function() {
        var controlDiv = $('<div />').attr('id', 'switcher');
        for (var i = 1; i <= featureCt; i++) {
            var control = $('<a href="#" class="selector" id="s' + i + '">' + i + '</a>');
            if (i == 1) control.addClass('selected first');
            if (i == featureCt) control.addClass('last');
            controlDiv.append(control);
        }
        $(this).append(controlDiv);
    });

	$("#fade").innerfade({
	    speed: 2000,
	    timeout: 5000,
	    containerheight: 262,
	    tracker: "switcher",
	    trackerclass: "selected",
	    repeat: 1
	});	
	$(".selector").click(function() {
        if($("#fade").data("timer")) {
            clearTimeout($("#fade").data("timer"));
            $("#fade").removeData("timer");
        }

        var id = Number(this.id.substr(1));
        $(".selector").removeClass("selected");
        $(this).addClass("selected");
        $("#fade>div:visible").fadeOut(2000);
        $("#fade>div").eq(id - 1).fadeIn(2000);
        return false;
    });
	
	// featured video links
    $('#video_top .rightcell .videoitem h3.title a, #video_top .videoitem .img a').click(function() {
        $('body.videocover #video_top .leftcell h3.title a').html(
            $(this).closest('.videoitem').find('h3.title').text()
        );
        $('body.videocover #video_top .leftcell p.date').html(
            $(this).closest('.videoitem').find('p.date').text()
        );
        $('body.videocover #video_top .leftcell .teaser').html(
            $(this).closest('.videoitem').find('.teaser').html()
        );
        
        var vid = $(this).closest('.videoitem').find('.video_url').text();
        ytPlayer.loadVideoByUrl(vid);
        return false;
    });

    // video carousel links
    
    $('#videocarousel h3.title a, #videocarousel .img a').click(function() {
        $('body.videocover #video_top .leftcell h3.title a').html(
            $(this).parent().parent().find('h3').text()
        );
        $('body.videocover #video_top .leftcell p.date').html(
            $(this).parent().parent().find('.date').text()
        );
        $('body.videocover #video_top .leftcell .teaser').html(
            $(this).parent().parent().find('.teaser').html()
        );

        var vid = $(this).parent().parent().find('.video_url').text();
        ytPlayer.loadVideoByUrl(vid);
        ytPlayer.playVideo();

        return false;
    });

    //video carousel, with a consistent height
    if ($('#videocarousel').length > 0) {
        var maxHt = 0;
        $('#videocarousel ul li').each(function() {
            if ($(this).height() > maxHt) maxHt = $(this).height();
        });
        $('#videocarousel').jCarouselLite({
            btnPrev: 'button.prev',
            btnNext: 'button.next',
            speed: 2000,
            visible: 6,
            scroll: 6,
            circular: true
        });
        $('#videocarousel ul li').css('height', maxHt);
    }

    //handlers for forms
    $("#email_address, #zip_code, #search_keywords, #user_name, #password").focus(function()	{
        vanilla.swapValue(this, false);
    });
    $("#email_address, #zip_code, #search_keywords, #user_name, #password").blur(function()	{
        vanilla.swapValue(this, true);
    });

	// clickable blog titles
	$('.blogitem').each(function() {
	    var url = $(this).find('.permalink').attr('href');
	    var txt = $(this).find('h1').text();
	    $(this).find('h1').html('<a href="' + url + '">' + txt + '</a>');
	});
	
	// size dropdowns to width of top item
	var maxWidth = 203;
    $('#topnav ul ul').css('width', 'auto');
    $('#topnav li li a').css('width', 'auto').css('white-space', 'nowrap');
    $('#topnav > ul > li').each(function(i) {
        $this = $(this);
        var widest = $this.width() - 22; // ul border and a padding
        
        $this.find('ul li a').each(function() {
            var w = $(this).width();
            if (w > widest) widest = w;
        });
        
        if (widest > maxWidth) {
            widest = maxWidth;
            $this.find('ul li a').css('white-space', 'normal');
        }
        $this.find('ul').css('width', widest + 20); // border is the extra +2
        $this.find('ul li a').css('width', widest);
    });

    // show/hide new member fields on contrib pages
    $("#id_this_is_a_payment_toward_an_existing_pledge").click( function() {
        if ($("#id_this_is_a_payment_toward_an_existing_pledge").attr("checked")) {
            $("#renew_fields").show();
        } else {
            $("#renew_fields").hide();
        }
    });
    
    // autogenerate slugs
    $('form#directory_listing_edit #name').keyup(function() {
        $('form#directory_listing_edit #slug').val(vanilla.text_to_slug(this.value));
    });
    
    // zebra strip3 directory tables
    $('table.entrylisting tr:even').addClass('alt');

    // hot up raw urls in directory listings
    $('body.directory_listing table.entrylisting td, body.directory_listing table.entrylist td').each(function() {
        var urlExp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&@#\/%?=~_|!:,.;]*[\-A-Z0-9+&@#\/%=~_|])/ig;
        var emailExp = /(\b[\w\.=-]+@[\w\.-]+\.[\w]{2,3})/g;
        var html = $(this).html().replace(urlExp, '<a href="$1">$1</a>').replace(emailExp, '<a href="mailto:$1">$1</a>');
        $(this).html(html);
        
    });
    
    // prepop current date in event search
    if ($('input[name=field_event_date_gte]').length > 0) {
        if (($('input[name=field_event_date_gte]').val() == '') && ($('input[name=field_event_date_lte]').val() == '') && ($('#messages').length == 0)) {
            $('input[name=field_event_date_gte]').val(vanilla.strftime('%m/%d/%Y'));
        }
    }


});




// CF thermometer
vanilla.addLoadEvent(function() {
    if (typeof vanilla.cf_data == 'undefined') {
        return;
    }
    
    // we delay this a bit so the user will see the entire effect
    setTimeout(function() {
        jQuery('#cf_progress #goal').html('$' + vanilla.format_number(vanilla.cf_data.goal));
        jQuery('#cf_progress #count').html(vanilla.cf_data.count + ((vanilla.cf_data.count == 1) ? ' donor' : ' donors'));
        jQuery('#cf_progress #average').html('$' + vanilla.format_number((vanilla.cf_data.raised/vanilla.cf_data.count).toFixed(2)));

        jQuery("#cf_progress").progressBar({
            value    : Math.round(vanilla.cf_data.raised * 100 / vanilla.cf_data.goal),
            height   : 190,
            width    : 32,
            callback : function(config) {
                var raised = 0;
                if (config.value > 0) {
                    raised = vanilla.format_number((vanilla.cf_data.raised * (config.runningValue / config.value)).toFixed(2));
                    raised = raised.replace('.00', '');
                }
                jQuery('#cf_progress #raised').html('$' + raised);
                
                if (config.runningValue == config.max) {
                    jQuery('#cf_progress').addClass('goal_reached');
                    jQuery('#cf_progress #scale').hide();
                }
                if (config.runningValue > config.max) {
                    jQuery('#cf_progress').addClass('goal_exceeded');
                    jQuery('#cf_progress #scale').hide();
                }
            }
        });
    }, 500);
});

