function clearSearchField(thefield){
    if (thefield.defaultValue==thefield.value)
        thefield.value = ""
}

function clearEmailField(thefield){
    if (thefield.defaultValue==thefield.value)
        thefield.value = ""
}

function initSponsors(){
    var sponsors = [];
    $("#sponsors-container");

    // console.log(sponsorsContainer);
}



/*
 * The following code eventually should be refactored into smaller, logical pieces.
 */

$(window).load(function() {
    /*
     * Sponsor logo distribution
     */
    var mask = $("#sponsors");
    var container = $("#sponsors-container");
    var sponsors = container.find("li");

    var w = 0;  // sum width of logos
    var n = 0;  // number of logos visible

    sponsors.each(function() {
        var thisWidth = $(this).outerWidth(true);

        // Does this logo not fit?
        if (w + thisWidth > mask.width()) {
            // Widen the container behind the mask
            container.width(container.width() + mask.width());

            // Add padding to distribute evenly
            var distributing = sponsors.filter("[distributing]");
            distributing.not(":last").css("paddingRight", ((mask.width() - w) / (n - 1)) + "px");
            distributing.removeAttr("distributing");

            // Reset
            w = n = 0;
        }
        n++;
        w += thisWidth;
        $(this).attr("distributing", "true");
    });

    var distributing = sponsors.filter("[distributing]");
    // Distribute logos on last page if extra space is < 1/5 container width
    if (mask.width() - w < mask.width() / 5) {
        distributing.not(":last").css("paddingRight", ((mask.width() - w) / (n - 1)) + "px");
    }
    distributing.removeAttr("distributing");

    function slideSponsorsRight() {
        if (!container.is(":animated")) {
            if (parseInt(container.css("marginLeft")) < 0) {
                container.animate({ marginLeft: "+=" + mask.width() + "px" });
            } else {
                container.animate({ marginLeft: -(container.width() - mask.width()) });
            }
        }
    }

    function slideSponsorsLeft() {
        if (!container.is(":animated")) {
            if (parseInt(container.css("marginLeft")) > -(container.width() - mask.width())) {
                container.animate({ marginLeft: "-=" + mask.width() + "px" });
            } else {
                container.animate({ marginLeft: 0 });
            }
        }
    }


    // Enable slider arrows
    $("#sponsors-left, #sponsors-right").css("visibility", "visible");
    $("#sponsors-left").click(function() {
        slideSponsorsRight();
        return false;
    });
    $("#sponsors-right").click(function() {
        slideSponsorsLeft();
        return false;
    });

    sponsorTimeoutID = 0;
    sponsorIntervalID = window.setInterval(function() { slideSponsorsLeft(); }, 15000);
    $("#sponsors-left, #sponsors-right").click(function() {
        window.clearTimeout(sponsorTimeoutID);
        window.clearInterval(sponsorIntervalID);
        sponsorTimeoutID = window.setTimeout(function() {
            sponsorIntervalID = window.setInterval(function() { slideSponsorsLeft(); }, 15000);
        }, 10000);
    });

    // Fix PNGs for IE6
    if ($.browser.msie && $.browser.version < 7) {
        var logos = container.find("img");
        logos = logos.add(".large-sponsor img");
        logos = logos.add(".small-sponsors img");
        logos.each(function() {
            $(this).width($(this).width());
            $(this).height($(this).height());
            $(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + $(this).attr("src") + "')");
            $(this).attr("src", "/images/main/1x1.gif");
        });
    }
});

$(document).ready(function() {
    /*
     * Accordion setup
     */
    $("#accordion").accordion({ autoHeight: false });

    // Hide ugly focus outline for IE.
    if ($.browser.msie) {
        $("#accordion > h3").each(function() { this.hideFocus = true; });
    }


    /*
     * Ajax search field
     */
    var submitTimeout;
    var resultsItemSelected = false;

    // Keypresses have a small delay before triggering form submission.
    $("#search input").keyup(function() {
        clearTimeout(submitTimeout);

        submitTimeout = setTimeout(function() {
            $("#search form").submit();
        }, 200);
    });

    // Form submission is hijacked to make only an ajax request.
    $("#search form").submit(function(e) {
        var input = $(this).find("input");
        if (input.val() != "") {
            $.ajax({
                url: $(this).attr("action"),
                data: input,
                complete: function() {
                    input.focus(); // Just in case
                },
                success: function(data) {
                    $("#search-results").html(data);
                }
            });
        } else {
            input.blur();   // Hide search results,
            input.focus();  // but keep focus on input field.
        }
        e.preventDefault();
    });

    // Hide search results after leaving search input field.
    $("#search input").blur(function() {
        // To ensure clicking a results item actually works.
        if (!resultsItemSelected) {
            $("#search-results").html("");
        }
    });

    // Add clickability to search results.
    $("#search-results li").live("click", function(e) {
        // Left click only
        if (e.button === 0) {
            location.href = $(this).find("a").attr("href");
        }
    });

    // To ensure clicking a results item actually works.
    $("#search-results li").live("mouseover", function() {
        resultsItemSelected = true;
    });
    $("#search-results li").live("mouseout", function() {
        resultsItemSelected = false;
    });


    /* ----- */

    /*
     * Slider for Schools page
     */
    var items = $(".slideshow-image");
    if (items.length > 4) {
        var container = $(".slideshow-image-container");
        var mask = container.parent();
        container.after('<div class="slideshow-navigation-container"><a href="#" class="schools-button" id="schools-right"></a><a href="#" class="schools-button" id="schools-left"></a><span>See more schools:</span></div>');
        container.width("9999px");
        mask.width("860px");
        mask.css("overflow", "hidden");
        $(window).load(function() {
            $("#schools-left").click(function() {
                if (parseInt(container.css("marginLeft")) < 0 && !container.is(":animated")) {
                    container.animate({ marginLeft: "+=" + items.outerWidth(true) + "px" });
                }
                return false;
            });
            $("#schools-right").click(function() {
                if (parseInt(container.css("marginLeft")) > -((items.length - 4) * items.outerWidth(true)) && !container.is(":animated")) {
                    container.animate({ marginLeft: "-=" + items.outerWidth(true) + "px" });
                }
                return false;
            });

            // Slide to the selected slideshow-image if necessary
            var currentSlideshowImage = $(".slideshow-image.current");
            var currentSlideshowImageIndex = currentSlideshowImage.prevAll(".slideshow-image").length + 1;
            if (currentSlideshowImageIndex > 4) {
                var slideBy = currentSlideshowImage.position().left;
                slideBy -= items.outerWidth(true) * 3;
                container.animate({ marginLeft: "-=" + slideBy + "px" });
            }
        });
    }



    /* ----- */


    /*
     * Newsletter ajax submission
     */
    $(".footer-email").submit(function() {
        var form = $(this);
        var submitButton = form.find("input[type=submit]");
        submitButton.remove();
        $.ajax({
            type: "POST",
            url: form.attr("action"),
            data: form.serialize(),
            success: function() {
                // console.log("Newsletter subscription succeeded");
            },
            error: function() {
                // We could look at the status to see what went wrong...
                // but we won't.

                // console.log("Newsletter subscription failed");
            },
            complete: function() {
                form.replaceWith('<div class="footer-email">Thank you for subscribing.</div>');
            }
        });

        return false;
    });


    /*
     * Add hover states for IE6
     */
    if ($.browser.msie && $.browser.version < 7) {
        // Top nav hover
        var hoverables = "#nav > ul > li,";
        // Search results
        hoverables += "#search-results li";

        // Hoverablify them thangs!
        $(hoverables).live("mouseover", function() {
            $(this).addClass("hover");
        });
        $(hoverables).live("mouseout", function() {
            $(this).removeClass("hover");
        });
    }
});

