var vanilla = {

    popup : function(p, h, w) {
        if (p != null) {
            var widgets = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,height=" + h + ", width=" + w;
            var popupWin = window.open(p, "popupWin", widgets);
        }
    },

    /* This function was originally used to pass parameters from a stub form to a full form,
       prefilling the values without having to trigger processing resulting in error messages. */

    getParams : function() {
        var query = decodeURI(location.search.substring(1));
        if (!query.length) return;
        var params = new Array();
        var pairs = query.split('&');
        for (var i = 0; i < pairs.length; i++) {
            var nameVal = pairs[i].split('=');
            params[nameVal[0]] = decodeURIComponent(nameVal[1]);
        }
        return params;
    },

    /* The following two functions are for those clients who refuse to follow best practices
       and insist that links open in a new window. By setting the class name of links to
       "newwindow", we allow javascript to do the work and avoid deprecated target attributes.

       credit: Roger Johansson (modified)
       http://www.456bereastreet.com/archive/200605/using_javascript_instead_of_target_to_open_new_windows/ */

    openInNewWindow : function(e) {
        var event;
        if (!e) {
            event = window.event;
        } else {
            event = e;
        }

        // Abort if a modifier key is pressed
        if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {
            return true;
        } else {
            // Change "_blank" to something like "newWindow" to load all links in the same new window
            var newWindow = window.open(this.getAttribute('href'), '_blank');
            if (newWindow) {
                if (newWindow.focus) {
                    newWindow.focus();
                }
                return false;
            }
            return true;
        }
    },

    /* We might need to know if someone is logged in. cookie.js is sometimes loaded in 
       the body of page in the login box block, so let's get a value ealier. */

    hasAuthCookie : function() {
        var pos = document.cookie.indexOf('auth_tkt=');
        if (pos != -1) {
            return true;
        } else {
            return false;
        }
    },

    /* The following three functions get, set, and delete cookies. They were first added
       to support better splash-page handling.

       credit: http://www.echoecho.com/jscookies02.htm (modified) */

    getCookie : function(name) {
        if (document.cookie.length > 0) {
            var begin = document.cookie.indexOf(name + '=');
            if (begin != -1) {
                begin += name.length + 1;
                var end = document.cookie.indexOf(";", begin);
                if (end == -1) end = document.cookie.length;
                return unescape(document.cookie.substring(begin, end));
            }
        }
        return null;
    },

    setCookie : function(name, value, expireDays, path, domain) {
        var expires = new Date ();
        expires.setTime(expires.getTime() + (expireDays * 24 * 3600 * 1000));
        document.cookie = name + "=" + escape(value) +
            ((expireDays == null) ? "" : "; expires=" + expires.toGMTString()) +
            ((path == null) ? "" : "; path=" + path) +
            ((domain == null) ? "" : "; domain=" + domain);
    },

    delCookie : function(name) {
        if (getCookie(name)) {
            document.cookie = name + "=" +
              "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    },

    cookie : {
        get : function(name) {
            if (document.cookie.length > 0) {
                var begin = document.cookie.indexOf(name + '=');
                if (begin != -1) {
                    begin += name.length + 1;
                    var end = document.cookie.indexOf(";", begin);
                    if (end == -1) end = document.cookie.length;
                    return unescape(document.cookie.substring(begin, end));
                }
            }
            return null;
        },
        /* vanilla.cookie.set(name, value, days, path, domain) */
        set : function(name, value, expireDays, path, domain) {
            var expires = new Date ();
            expires.setTime(expires.getTime() + (expireDays * 24 * 3600 * 1000));
            document.cookie = name + "=" + escape(value) +
                ((expireDays == null) ? "" : "; expires=" + expires.toGMTString()) +
                ((path == null) ? "" : "; path=" + path) +
                ((domain == null) ? "" : "; domain=" + domain);
        },
        /* vanilla.cookie.del(name) */
        del : function(name) {
            if (vanilla.cookie.get(name)) {
                document.cookie = name + "=" +
                    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
            }
        }
    },
    
    /* This function is used on dropdown menus to send users to a new URL */

    jumpTo : function(select) {
        var url = select[select.selectedIndex].value;
        if (!url) return;
        window.location = url;
    },

    /* This function is used to toggle the values in certain form fields without field labels */

    swapValue : function( field, revert, defValue ) {
        if (defValue == undefined) defValue = field.defaultValue;
	    if (field.value == (revert ? '' : defValue)) {
	        field.value = (revert ? defValue : '');
	    }
	},

    /* The following two methods are deprecated and included only for template support
       as we move to jQuery */

    getElementById : function(id) {
        if (document.getElementById) {
            return document.getElementById(id);
        } else if (document.all) {
            return document.all[ id ];
        } else {
            return null;
        }
    },

    addLoadEvent : function(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (oldonload) oldonload(); // use conditional to keep IE7 happy
                func();
            }
        }
    }
}

jQuery.noConflict();
jQuery(document).ready(function($) {
    /******
    These tie into the reference templates and style sheets and/or 
    represent new standard behaviors.
    ******/

    // enable tabs on lte and call radio forms
    $("#tab-tp a").click(function() {
        $("#tab-wt").removeClass("show");
        $("#text-wt").removeClass("show");
        $("#tab-tp").addClass("show");
        $("#text-tp").addClass("show");
    });
    $("#tab-wt a").click(function() {
        $("#tab-tp").removeClass("show");
        $("#text-tp").removeClass("show");
        $("#tab-wt").addClass("show");
        $("#text-wt").addClass("show");
    });

    // set and unset values in amount fields on contribute forms
    $("input[name=amount]").not("#id_amount_other_btn").click(function() {
        $("#id_amount_other").val("");
    });
    $("#id_amount_other").blur(function() {
        if ($(this).val() == "") {
            $("#id_amount_other_btn").attr("checked", false);
        } else {
            $("#id_amount_other_btn").attr("checked", true);
        }
    });

    // add a class to the body element for browser-specific style-hooks
    var classStr = "unknown_ua";
    if (jQuery.browser.safari) {
        classStr = "safari";
    } else if (jQuery.browser.opera) {
        classStr = "opera";
    } else if (jQuery.browser.msie) {
        classStr = "msie";
    } else if (jQuery.browser.mozilla) {
        classStr = "mozilla";
    }
    $("body").addClass(classStr);

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

    // focus on first form field
    $("body.form input:visible:enabled:first").focus();

    // handler for checkbox on membership pages
    $("#id_billing_info_same").change( function() {
        if ($("#id_billing_info_same").attr("checked")) {
            $("#billing_info").hide();
        } else {
            $("#billing_info").show();
        }
    });

    // jazz up ampersands in headers (http://patrickhaney.com/thinktank/2008/08/19/automatic-awesompersands)
    $("h1:contains('&'), h2:contains('&'), h3:contains('&')", document.body).contents().each(function() {
        if( this.nodeType == 3 ) {
            $(this).replaceWith(this.nodeValue.replace(/&/g, "<span class='amp'>&</span>"));
        }
    });

    // open certain classed links in new window
    $("a.newwindow").each(function() {
        $(this).css("padding-right", "18px").css("background", "url(/images/newwindow.png) no-repeat right").click(vanilla.openInNewWindow);
    });

    /******
    These are optional, and can be deleted if not used.
    ******/

    // enable nav hover for dropdowns in IE6
    $("#topnav>ul").children("li").hover(
        function () {
            $(this).addClass("over");
        },
        function () {
            $(this).removeClass("over");
        }
    );

    // rounded corners
    var roundStr = '<b class="cn tl"></b><b class="cn tr"></b><b class="cn bl"></b><b class="cn br"></b>';
    $(".round").addClass("boxc").append(roundStr);

    // handlers for fields in signup stub form
    $("#updates_email, #updates_zip, #search_keywords").focus(function() {
        vanilla.swapValue(this, false);
    });
    $("#updates_email, #updates_zip, #search_keywords").blur(function() {
        vanilla.swapValue(this, true);
    });
    
    // share icons
    $("#bookmarks").bookmark({
        icons: "/images/bookmarks.png", 
        sites: ["delicious", "digg", "facebook", "fark", "google", "kaboodle", "mixx", "propeller", "reddit", "stumbleupon", "technorati", "twitthis", "yahoobuzz"]
    });
    $("#bookmarks ul").prepend('<li class="share">Share &#160;</li>');

    // rotating background images on homepage
    /*vanilla.bg_num = 2;
    $("#home_top").addClass('bg' + vanilla.bg_num);
    setInterval (function() {
        $("#home_top").removeClass('bg' + vanilla.bg_num);
        vanilla.bg_num++;
        if (vanilla.bg_num > 4) {
            vanilla.bg_num = 2;
        }
        $("#home_top").addClass('bg' + vanilla.bg_num);
    }, 15000);*/
    
    // twitter feed on video page
    // $('#twitterfeed').twitterFeed({query : 'sotomayor'});

    // twitter feed on demo page
    $('#twitterdemo').twitterFeed({query : 'sotomayor'});
    
    // preload bg images for homepage
    //$('<img>').attr('src', '/images/bg_home_top3.jpg');
    //$('<img>').attr('src', '/images/bg_home_top4.jpg');

});
