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";
        }
    },

    /* 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();
            }
        }
    },
    
    /* The following two methods are used by the "Count Your Blessings" pages in /blessings/ */
    
    countBlessings : function(el) {
        var blessings = 0;
        jQuery(".threecol input:checkbox").each(function() {
            if (jQuery(this).attr("checked")) {
                blessings += 1;
            }
        });
        var url = jQuery(el).attr("href") + blessings;
        jQuery(el).attr("href", url);
    },
    
    displayBlessings : function() {
        var params = vanilla.getParams();
        if ((typeof params != undefined) && params.count) {
            var html = "<p>You checked <strong>" + params.count + "</strong> blessing" + (params.count > 1 ? "s" : "") + ". Great! Now, let's multiply your total amount of blessings by <em>Chai</em>: " + params.count + " x 18 = " + (params.count * 18) + ".</p>";
            html += "<p>Your recommended donation is: <strong>$" + (params.count * 18) + "</strong>.</p>";
            jQuery("#results_container").append(html).show();
            jQuery("#failed_container").hide();
        }
    
    }
}

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>"));
        }
    });

    /******
    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);
    if (jQuery.browser.mozilla) {
        $("body.is_form form button").each(function() {
            var label = $(this).html();
            $(this).addClass("unboxc").html('<div class="boxc">' + label + roundStr + '</div>' );
        });       
    } else {
        $("body.is_form form button").addClass("boxc").append(roundStr);
    }

    // handlers for fields in signup stub form
    $("#signup_box_email, #signup_box_zip, #login_email, #login_password").focus(function() {
        vanilla.swapValue(this, false);
    });
    $("#signup_box_email, #signup_box_zip, #login_email, #login_password").blur(function() {
        vanilla.swapValue(this, true);
    });

    // open certain 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);
    });
    $("a.newwindow_noicon").each(function() {
        $(this).click(vanilla.openInNewWindow);
    });
    
    // side homepage signup/signin boxes if logged in
    if (vanilla.hasAuthCookie()) {
        $("#home_register").hide();
        $("#home_login").hide();
    }
    
    // enable the check all checkbox on cf edit page
    $("#checkall").change(function() {
        if ($("#checkall").attr("checked")) {
            $(".amount input").attr("checked", "checked");
        } else {
            $(".amount input").attr("checked", "");
        }
    });

	// handler for checkbox on contribute pages
    $("#id_dedicate_gift").click( function() {
        if ($("#id_dedicate_gift").attr("checked")) {
            $("#dedicate_fields").show();
        } else {
            $("#dedicate_fields").hide();
        }
        $("#middle b.bot").css("bottom", "1px");
        setTimeout(function() { $("#middle b.bot").css("bottom", 0); }, 200);
    });

});

