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

    switchStyles : function(styleName) {
        $("link[@rel*=style][title]").each(function(i) {
            this.disabled = true;
            if (this.getAttribute('title') == styleName) this.disabled = false;
        });
        vanilla.setCookie('style', styleName, 365, '/');
    },
    
    /* 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();
            }
        }
    }
}

$(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() {
        console.log("clicked tab-tp");
        $("#tab-wt").removeClass("show");
        $("#text-wt").removeClass("show");
        $("#tab-tp").addClass("show");
        $("#text-tp").addClass("show");
    });
    $("#tab-wt a").click(function() {
        console.log("clicked tab-wt");
        $("#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);

    // handlers for fields in signup stub form
    $("#signup_box_email").focus(function() {
        if (this.value == "Email Address") this.value = "";
    });
    $("#signup_box_email").blur(function() {
        if (this.value == "") this.value = "Email Address";
    });
    $("#signup_box_zip").focus(function() {
        if (this.value == "Zip Code") this.value = "";
    });
    $("#signup_box_zip").blur(function() {
        if (this.value == "") this.value = "Zip Code";
    });

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

    // rotate thru a set of divs -- this ties into innerfade.js
    // edit to change default options
    $('#fade').innerfade({
        speed: 2000,
        timeout: 8000,
        containerheight: 270,
        tracker: 'switcher',
        trackerclass: 'selected'
    });

    $('#stop').click(function() {
        clearTimeout($('#fade').data('timer'));
        $('#fade').removeData('timer');
        $('#stop').hide();
        $('#start').show();
        return false;
    });


    $('#start').click(function() {
        $('#start').hide();
        $('#stop').show();
        $('.selector').removeClass('selected');
        $('#fade').innerfade({
            speed: 2000,
            timeout: 8000,
            containerheight: 270,
            tracker: 'switcher',
            trackerclass: 'selected'
        });
        var id = $('#fade').data('next');
        $('#' + id).addClass('selected');
        return false;
    });

    $('.selector').click(function() {
        if (this.id == 'stop' || this.id == 'start') {
            return;
        }

        if($('#fade').data('timer')) {
            clearTimeout($('#fade').data('timer'));
            $('#fade').removeData('timer');
            $('#stop').hide();
            $('#start').show();
        }

        var id = Number(this.id.substr(1));
        $('.selector').removeClass('selected');
        $(this).addClass('selected');
        $('#fade li:visible').fadeOut(2000);
        $('#feature_' + id).fadeIn(2000);
        var num = $('#fade').data('num_elements');
        if (id < num) {
            $('#fade').data('next', id);
        } else {
            $('#fade').data('next', 0);
        }
        return false;
    });

    /******
    Site-specific additions
    ******/

    $("#login_box a.showhelp").click(function() {
        $("#login_box .help").show();
    });
    $("#login_box .help .close").click(function() {
        $("#login_box .help").hide();
    });
    
    // sidebar event search zip field
    $("#id_event_zip").focus(function() {
        if (this.value == "ZIP Code") this.value = "";
    });
    $("#id_event_zip").blur(function() {
        if (this.value == "") this.value = "ZIP Code";
    });

    // dropdowns for community bookmarks
    $("#posttool").hover(
        function () {
            $("#posttool ul").show();
        },
        function () {
            $("#posttool ul").hide();
        }
    );

    // social bookmarking links
    $("#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>');
    
    // style switcher
    $("#textsize a").click(function() {
        vanilla.switchStyles(this.getAttribute("rel"));
        return false;
    });
    var style = vanilla.getCookie("style");
    if (style) vanilla.switchStyles(style);

    // pass extra info to processor
    $('form#contribution_form').submit(function() {
        if ($('select[name=donation_region]').length && $('textarea[name=comments_donation]').length) {
            $("#field_comment1").val("description");
            $("#field_comment2").val("invoice_number");
            
            $('#value_comment1').val($('textarea[name=comments_donation]').val());
            $('#value_comment2').val($('select[name=donation_region] option:selected').val());
        }
        return true;
    });

});
