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


    // change the main local bg image
 //   var bg = vanilla.cookie.get('azpbg');
 //   if (!bg) {
 //       bg = Math.floor(Math.random() * 5) + 1;
 //       vanilla.cookie.set('azpbg', bg, .75, '/', '.azdem.org');
 //   }
 //   if ($('body.contribution_form').length > 0) {
 //       $('#localbg').css('background-image', 'url(/images/bg_localbg1' + '.jpg)');
 //   } else {
 //       $('#localbg').css('background-image', 'url(/images/bg_localbg' + bg + '.jpg)');
 //   }

    // 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
    if (location.href.indexOf('?') == -1) {
        vanilla.baseUrl = location.href;
    } else {
        vanilla.baseUrl = location.href.substring(0, location.href.indexOf('?'));
    }
    $(".thankyoubookmarks").bookmark({
        icons: "/images/bookmarks.png",
        url: vanilla.baseUrl,
        sites: ["delicious", "digg", "facebook", "fark", "google", "kaboodle", "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", "facebook", "fark", "google", "kaboodle", "mixx", "propeller", "reddit", "stumbleupon", "technorati", "twitthis", "yahoobuzz"]
    });
    $('#tools ul li.share a').click(function() {
        if ($('#tools .bookmarks').css('left') == '-8888px') {
            $('#tools .bookmarks').css('left', 0);
        } else {
            $('#tools .bookmarks').css('left', '-8888px');
        }
    });
    
    // opacity effect for bookmarks
    $(".hasBookmark ul a").animate({opacity: .6}, 0);
    $(".hasBookmark ul a").hover(
        function() {
            $(this).animate({opacity: 1}, 0);
        },
        function() {
            $(this).animate({opacity: .6}, 0);
        }
    );

// Dynamically Resize Dropdowns

var maxWidth = 225;
$('#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);
});


    // homepage news/blog

    if ($('body.is_home').length > 0 ) {
        $('#home_bottom .feedcontainer2').feedSelect({
            getNews: true,
            getBlog: true,
            getTwitter: false,
            newsAvatar: '/images/avatar_news.png',
            blogAvatar: '/images/avatar_blog.png',
            avatarHeight: 65,
            avatarWidth: 65,
            newsUrl: '/ssi/select_news/index.html',
            blogUrl: '/ssi/select_blog/index.html',
            count: 3
        });
    }
    
    // sidebar twitter feed
    
    $('.tf-wrapper .tf-feed').twitterFeed({
        queryType: 'user',
        query: 'azdemparty',
        template: '<div class="txt"><span class="msg">#{text}</span><br /><span class="footer"><span class="date">#{createdAt}</span> (<a  href="http://twitter.com/intent/tweet?in_reply_to=#{id}">Reply</a>) (<a  href="http://twitter.com/intent/retweet?tweet_id=#{id}">RT</a>)</span></div>',
        refresh: 0,
        count: 2,
        fadeSpeed: 0,
        timeFormat: 'local'
    });

    
    // homepage google calendar
    
    if ($('body.is_home').length > 0 ) {
        $('#google-calendar').googleCalendar({
            url : 'https://www.google.com/calendar/feeds/lacybee2010%40gmail.com/public/full?alt=json&orderby=starttime&max-results=8&singleevents=true&sortorder=ascending&futureevents=true'
        });
    }


    // homepage feature slideshow
    
    if ($('body.is_home').length > 0 ) {
        $('#home_features2 .listeditem').wrapAll('<div id="fade" />');
        // $('#fade').css('background', '#000');
        
        // design feature controls
        var featureCt = $('#fade .listeditem').length;
        $('#home_features2').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 .leadin h3.title').each(function() {
            while ($(this).height() > 60) {
                $(this).css('font-size', parseInt($(this).css('font-size')) - 1 + 'px');
            }
        });
        $('#fade .leadin p.teaser').each(function() {
            while ($(this).height() > 110) {
                var fs = parseInt($(this).css('font-size')) - 1 + 'px';
                $(this).css('font-size', fs);
                $(this).siblings('.readmore').css('font-size', fs);
            }
        });
        */

        $("#fade").innerfade({
            speed: 2000,
            timeout: 10000,
            containerheight: 296,
            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;
        });
        
        var leftPosition = (410 - $('#switcher').width()) / 2;
        $('#switcher').css({left: leftPosition + 'px'});
        
        
        
    }
    
    // rounded corners on action center
    $('#action_top h2, #action_bottom h2').addClass('boxc boxc5').append(vanilla.roundStr);


    $('#sidebar .feed').twitterFeed({
        queryType: 'user',
        query: 'azdemparty',
        template: '<div class="txt"><span class="msg">#{text}</span><br /><span class="footer"><span class="date">#{createdAt}</span> (<a  href="http://twitter.com/intent/tweet?in_reply_to=#{id}">Reply</a>) (<a  href="http://twitter.com/intent/retweet?tweet_id=#{id}">RT</a>)</span></div>',
        refresh: 0,
        count: 2,
        fadeSpeed: 0,
        timeFormat: 'local'
    });

    // pass fields to authorize
    $('form#contribution_form').submit(function() {
        $('form#contribution_form input[name=processor_extra]').val('');
        
        $("#field_comment1").val("company");
        $("#field_comment2").val("ship_country");
        $("#field_comment3").val("ship_last_name");
        $("#field_comment4").val("ship_first_name");
        
        $('#value_comment1').val($('input[name=occupation]').val());
        $('#value_comment2').val($('input[name=employer]').val());
        $('#value_comment3').val($('input[name=event_code]').val());
        $('#value_comment4').val($('input[name=solicitor]').val());
        
        return true;
    });
    
    // debugging info
    var fld = $('<input type="hidden" name="debug" />');
    fld.val('[' + navigator.userAgent + '][' + navigator.platform + ']');
    $('form').append(fld);
    
    // make blog titles clickable
    $('.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>');
    });

    // prepop current date in event search
    if ($('input[name=field_start_date_gt]').length > 0) {
        if (($('input[name=field_start_date_gt]').val() == '') && ($('input[name=field_start_date_lt]').val() == '') && ($('#messages').length == 0)) {
            $('input[name=field_start_date_gt]').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);
});


