$(function() {
    initOverLabels();
    $("ul.piped-list>li:not(:last-child)").append("<span>|</span>");
    $("#Print").click(function() { window.print(); return false; });

    // search box
    $("#SearchBox h2").click(function() {
        $("#SearchBox fieldset").hide();
        $("#SearchBox h2").removeClass("selected");
        $(this).addClass("selected").next("fieldset").show();
    }).css("cursor", "pointer").css("position", "absolute");
    $("#SchoolSearch h2").click();

    // landing page hovers
    $("#interim .supplement").hover(function() {
        if ($("h3 a", this).length > 0) {
            $(this).addClass("supplement-hover");
            window.status = $("h3 a", this).attr("href");
        }
    }, function() {
        if ($("h3 a", this).length > 0) {
            $(this).removeClass("supplement-hover");
            window.status = "";
        }
    }).click(function() {
        if ($("h3 a", this).length > 0) {
            window.location = $("h3 a", this).attr("href");
        }
    });

    // school drop downs
    $("#School>h3, #School>img").click(function() {
        $("#School>ul").toggle();
    });

    // Rollover script for the Social media bookmarks in the footer.
    $("ul.social").imageSwap();

    // IE6 hack
    /*@cc_on
    @if (@_jscript_version <= 5.7)
    try {
        document.execCommand("BackgroundImageCache", false, true);
    } catch (e) { }

    if ($("#masthead").length > 0)
        $("#components").css("position", "absolute").css("top", $("#masthead")[0].offsetHeight + "px").css("right", "0px").css("height", "1%").insertAfter("#footer");
    @end
    @*/

    // Interactive Maps
    var $maps = $("#content>.html-content>.maps");
    if ($maps.length > 0) {
        // link click event
        $("ul>li>a", $maps).hover(function() {
            var $this = $(this);
            $(">p", $maps).hide();
            $("#" + $this.parent().attr("id").replace(/Link/, "Map")).show();
        }, function() {
            $(">p", $maps).hide();
            $("#EDMap").show();
        });

        // set All locations as default selected
        $(">p", $maps).hide();
        $("#EDMap").show();
    }

    // equal height for #primary-navigation and #content
    setMainEqualHeight(); // wait until load?

    // equal height for Case Study pages
    setCSEqualHeight();

    // equal height for landing page boxes
    setLandingHeight();

    // see if sidebar images are missing the preceding text
    var $sideImage = $("#components .SingleImage1_plcSideContent1");
    if ($sideImage.length == 1 && $sideImage.prev(".supplement").length == 0) {
        $sideImage.css("margin-top", "165px");
    }
});

$(window).load(function () {
	// make sure the height hasn't been affected by any other content
	setMainEqualHeight();
	setCSEqualHeight();
	setLandingHeight();
});

function setMainEqualHeight()
{
	// makes sure that content and primary nav containers are at least the size of component container and are as tall as each other
	var $columns = $("#primary-navigation, #content, #components");
	if ($columns.length > 0)
	{
		setEqualHeight($columns, $columns);
	}
}

function setCSEqualHeight()
{
	// makes sure that supplementary content containers are all the same height
	var $supplements = $("#interim div.supplement div.body");
	if ($supplements.length === 3)	// match only 3 for CS pages
	{
		setEqualHeight($supplements, $supplements);
	}
}

function setLandingHeight()
{
	// makes sure that supplementary content containers are all the same height
	var $supplements = $("#interim div.supplement h2");
	if ($supplements.length === 4)	// match only 4 for landing pages
	{
		setEqualHeight($supplements, $supplements);
		
		// make sure bodies are equal height as well.
		$supplements = $("#interim div.supplement div.body");
		if ($supplements.length === 4)	// match only 4 for landing pages
		{
			setEqualHeight($supplements, $supplements);
		}
	}
}

// equal height code
function setEqualHeight($toMeasure, $toResize) {
	if ($toMeasure.length > 0 && $toResize.length > 0) {
		// set back to auto for dynamic content
		$toResize.css("height", "auto");
		
		var heights = [];
		for (var i = 0; i < $toMeasure.length; i++) {
			heights[i] = $toMeasure[i].offsetHeight;
		}
		var maxHeight = getMax(heights);

		// check max of min-height's + padding for objects to set (if possible)
		var minheights = [maxHeight];
		try {
			for (var i = minheights.length; i < $toResize.length; i++) {
				var newMin = getOffsetMin($($toResize[i]));
				if (!isNaN(newMin))
					minheights[i] = newMin;
			}
		} catch(e) {};
		maxHeight = getMax(minheights);
		
		$toResize.each(function (i) {
			var $this = $(this);
			$this.css("height", (maxHeight - getVPaddingOffset($this)) + "px");
		});
	}
}

function getMinHeight($object) {
	return parseInt($object.css("min-height"), 10);
}

function getVPaddingOffset($object) {
	var top = parseInt($object.css("padding-top"), 10);
	var bottom = parseInt($object.css("padding-bottom"), 10);
	return (top + bottom);
}

function getOffsetMin($object) {
	return (getMinHeight($object) + getVPaddingOffset($object));
}

function getMax(numArray) {
	if (numArray.length > 1) {
		var newMax = numArray[0];
		for (var i = 0; i < numArray.length; i++) {
			newMax = Math.max(newMax, numArray[i]);
		}
		return newMax;
	} else if (numArray.length == 1) {
		return numArray[0];
	}
	return 0;	// error
}

// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,"",-1);
}
// /cookie functions

function initOverLabels() {
	$("label.overlabel[@for]").each(function() {
		var label = $(this);
		label.attr("class", "overlabel-apply");
		var field = $("#" + label.attr("for"));
		if (field.val() != "")
			label.hide();
		field.focus(function() {
			label.hide();
		}).blur(function() {
			if (field.val() == "")
				label.show();
		});
		label.click(function() {
			field.trigger("focus");
		});
	});	
}

// used for links to objects like video. This will overlay the video on the screen. Requires jqModal.js.
$.fn.objectOverlay = function(w, h) {
	$(this).click(function() {
		var vid = $(this).attr("href");
		var objtag = "<div class=\"jqmWindow\">";
		objtag += "<a id=\"object-close\" class=\"jqmClose\" href=\"javascript:void(0);\">close X</a>";
		objtag += "<object id=\"vid\" width=\"" + w + "\" height=\"" + h + "\" data=\"" + vid + "\">";
		objtag += "<param name=\"src\" value=\"" + vid + "\"/>";
		objtag += "<p>Video for " + vid + "</p>";
		objtag += "</object></div>";
		$(objtag).appendTo("body").jqm({onHide: function(hash) {
			hash.w.remove();
			hash.o.remove();
			if ($.browser.msie)
				document.location = document.location;
		}}).jqmShow();
		return false;
	});
};

function pluralize(word, count) 
{
	var plural = "";
	if (count != 1) 
	{
		switch (word)
		{
			case "match":
				plural = "es";
				break;
			default:
				plural = "s";
				break;
		}
	}
	return count + " " + word + plural;
}

$.fn.imageSwap = function() {
    var $parentElement = this;

    var cache = [];

    //preload the active images before use.
    var imageSrc = $parentElement.find("img").get();
    for (var i = imageSrc.length; i--; ) {
        var cacheImage = document.createElement('img');
        cacheImage.src = imageSrc[i].src.replace("_off", "_on");
        cache.push(cacheImage);
    }

    //Events for mouseover mouseout on the images within the parentElement that was passed in.
    $parentElement.find("img").bind("mouseover", function() {
        var $img = $(this);
        $img.attr("src", $img.attr("src").replace("_off", "_on"));
    }).bind("mouseout", function() {
        var $img = $(this);
        $img.attr("src", $img.attr("src").replace("_on", "_off"));
    });
};

$.extend({
    inArray: function( elem, array, start ) {
        if (start == null)
            start = 0;
            
		for ( var i = start, length = array.length; i < length; i++ )
			if ( array[ i ] == elem )
				return i;

		return -1;
	},
	
	inArrayAll: function( elem, array ) {
	    var indices = [];
        var idx = $.inArray(elem, array, 0);
        while (idx != -1)
        {
            indices.push(idx);
            idx = $.inArray(elem, array, idx + 1);
        }
        
        return indices;
	}
});