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

    getNewWindowLinks : function() {
        if (!document.getElementsByTagName && !document.createElement) return false;

        // Change this to the text you want to use to alert the user that a new window will be opened
        var strNewWindowAlert = " (opens in a new window)";

        // Find all links
        var links = document.getElementsByTagName('a');
        for (var i = 0; i < links.length; i++) {
            var link = links[i];
            if (/\bnewwindow\b/.test(link.className)) {
                // Create an em element containing the new window warning text
                var objWarningText = document.createElement("em");
                objWarningText.appendChild(document.createTextNode(strNewWindowAlert));
                link.appendChild(objWarningText);
                link.onclick = vanilla.openInNewWindow;
            }
        }
    },

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

    /* 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() {
    $('a.lightbox').lightBox();
    // 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);

    // jagged borders for top images
    var imgTopBorderStr = '<b class="btop"></b>';
    var imgBotBorderStr = '<b class="bbot"></b>';

    $(".jagged").not(".nobtop").append(imgTopBorderStr);
    $(".jagged").not(".nobbot").append(imgBotBorderStr);

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

    // handlers for email field in signup stub form
    $("#signup_email").focus(function() {
        if (this.value == "Email Address") this.value = "";
    });
    $("#signup_email").blur(function() {
        if (this.value == "") this.value = "Email Address";
    });

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

    // open certain links in new window
    vanilla.getNewWindowLinks();

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

    // rotate images on homepage

    $('#fade').innerfade({
        speed: 10,
        timeout: 4000,
        containerheight: 311,
        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: 10,
            timeout: 8000,
            containerheight: 311,
            tracker: 'switcher',
            trackerclass: 'selected'
        });
        var id = $('#fade').data('next');
        $('#' + id).addClass('selected');
        return false;
    });

    $('.selector').click(function() {
        // make links go to real urls
        return true;
        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);
        $('.selector').removeClass('selected');
        $(this).addClass('selected');
        $('#fade li:visible').fadeOut(10);
        $('#feature_' + id).fadeIn(10);
        var num = $('#fade').data('num_elements');
        if (id < num) {
            $('#fade').data('next', id);
        } else {
            $('#fade').data('next', 0);
        }
        return false;
    });
});
