var screenData = function() {
	if (self.innerHeight) {
		screenData.pageYOffset = self.pageYOffset;
		screenData.pageXOffset = self.pageXOffset;
		screenData.innerHeight = self.innerHeight;
		screenData.innerWidth = self.innerWidth;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		screenData.pageYOffset = document.documentElement.scrollTop;
		screenData.pageXOffset = document.documentElement.scrollLeft;
		screenData.innerHeight = document.documentElement.clientHeight;
		screenData.innerWidth = document.documentElement.clientWidth;
	} else if (document.body) {
		screenData.pageYOffset = document.body.scrollTop;
		screenData.pageXOffset = document.body.scrollLeft;
		screenData.innerHeight = document.body.clientHeight;
		screenData.innerWidth = document.body.clientWidth;
	}
	return screenData;
};

function initPageHeight() {
	return;
	var lch = $(".leftnav").height(); //lch - left column height
	var pbh = $(".page-body").height(); //pbh = page body height
	var rch = $(".rightnav").height(); //rch = right column height

	if (lch > rch && lch > pbh){
		$(".page-body").css("height", lch + "px");
		$(".rightnav").css("height", lch + "px");
	}

	if (rch > lch && rch > pbh){
		$(".page-body").css("height", rch + "px");
		$(".leftnav").css("height", rch + "px");
	}

	if (pbh > rch && pbh > lch){
		$(".leftnav").css("height", pbh + "px");
		$(".rightnav").css("height", pbh + "px");
	}

	$(".fill-height").each(function() {
		var regex = new RegExp("\\D", "g");

   		$(this).height($(this).parent().height() -
   				( $(this).offset().top - $(this).parent().offset().top ) +
   				$(this).parent().css("border-top-width").replace(regex,"") * 1  +
   				( $(this).parent().css("padding-top").replace(regex,"")  * 1 +
   				  $(this).parent().css("padding-bottom").replace(regex,"")  * 1 ) -
   				( $(this).css("padding-top").replace(regex,"")  * 1   +
   				  $(this).css("padding-bottom").replace(regex,"")  * 1  ) -
   				( $(this).css("border-top-width").replace(regex,"")  * 1  +
   				  $(this).css("border-bottom-width").replace(regex,"")  * 1)
   		);
	  });
}

//assume 1024x768 background graphics
var hMultiplier = 1.333; // 1024/768
var wMultiplier = .75; // 768/1024
var getProportionalData = function(screenObj) {
	var w = screenObj.innerWidth;
	var h = screenObj.innerHeight;
	if (h * hMultiplier > w) {
		w = h * hMultiplier;
	}
	else {
		h = w * wMultiplier;
	}
	getProportionalData.height = h;
	getProportionalData.width = w;
	return getProportionalData;
};

var bigWindowMode = true;
function adjustBGImage(firstTime) {
	var screenObj = new screenData();
	if (screenObj.innerWidth < 940) {
		if (bigWindowMode) {
			$("#bg_image").hide();
			$("body").css("overflow", "auto");
			$("#outer_wrap").css("overflow", "auto");
			bigWindowMode = false;
		}
	} else {
		if (!bigWindowMode) {
			$("#bg_image").show();
			$("body").css("overflow", "hidden");
			$("#outer_wrap").css("overflow", "scroll");
			bigWindowMode = true;
		}
		var resizeObj = new getProportionalData(screenObj);
		$("#bg_image > img").width(resizeObj.width);
		$("#bg_image > img").height(resizeObj.height);
		if (firstTime) {
			$("#bg_image").show();
		}
	}
}

$(function(){
	$(".button").assignMouseEvents();
	adjustBGImage(true);
	$(window).resize(adjustBGImage);
});


// Old style functions
var signUpInstructions = "your email address";

function doSignUpFocus(component) {
    var val = component.value;
    if (val == signUpInstructions) {
        component.value = "";
    }
}

function doSignUpBlur(component) {
    var val = component.value;
	if (strTrim(val) == '') {
		 component.value = signUpInstructions;
    }
}

// Old style functions
var searchInstructions = "keyword or item #";

function submitSearchForm(theForm) {
	   if(doSearchValidation (theForm)) theForm.submit();	
}
	
function doSearchFocus(component) {
    var searchVal = component.value;
    if (searchVal == searchInstructions) {
        component.value = "";
    }
}

function doSearchBlur(component) {
    var searchVal = component.value;
    if (strTrim(searchVal) == '') {
        component.value = searchInstructions;
    }
}

function doSearchValidation (theForm) {
	var searchVal = theForm.keyword_entry.value;
	theForm.keyword.value = theForm.keyword_entry.value;
	if (searchVal == "" || searchVal == searchInstructions) {
		alert ("Please enter a search term and try your search again") ;
		return false ;
	}
	return true ;
}

function strTrim(s) {
    // Remove leading spaces and carriage returns
    while (s.substring(0,1) == ' ') {
        s = s.substring(1, s.length);
    }
    // Remove trailing spaces and carriage returns
    while (s.substring(s.length-1, s.length) == ' ') {
        s = s.substring(0, s.length-1);
    }
    return s;
}

/*
 * This function launches a new web browser window to a specified width, height and features.
 * Features string is a comma separated window's feature needed for this new window. For Instance
 * If a new window needs a toolbar the feature string must be "toolbar" like needs scroll bar and
 * and toolbar then it must be "toolbar,scrollbar". Note that the order of the feature is not required.
 * Also it's case insensitive. Therefore, "scrollbar,toolbar" is identical to "Toolbar,ScrollBar".
 *
 * If the features string is ommitted then all the features are turned off. To turn all the features on
 * use the word "all" for features instead of specifying each feature.
 */

function openWindow(address, width, height,features)
{
	/* Find out what features need to be enable
	 *
   */
	if(features)
		features = features.toLowerCase();
	else
		features = "";

	var toolbar = (features == "all" ? 1 : 0);
	var menubar = (features == "all" ? 1 : 0);
	var location = (features == "all" ? 1 : 0);
	var directories = (features == "all" ? 1 : 0);
	var status = (features == "all" ? 1 : 0);
	var scrollbars = (features == "all" ? 1 : 0);
	//var resizable = (features == "all" ? 1 : 0);
	var resizable = 1;

	if(features != "all")
	{
		//split features
		var feature = features.split(",");
		for(i = 0; i < feature.length; i++)
		{
		 	if(feature[i] == "toolbar")
			   toolbar = 1;
			else if(feature[i] == "menubar")
			   menubar = 1;
			else if(feature[i] == "location")
			   location = 1;
			else if(feature[i] == "directories")
			   directories = 1;
			else if(feature[i] == "status")
			   status = 1;
			else if(feature[i] == "scrollbars")
			   scrollbars = 1;
			else if(feature[i] == "resizable")
			   resizable = 1;
		}

	}
	features = "toolbar=" + toolbar + ",";
	features += "menubar=" + menubar + ",";
	features += "location=" + location + ",";
	features += "directories=" + directories + ",";
	features += "status=" + status + ",";
	features += "scrollbars=" + scrollbars + ",";
	features += "resizable=" + resizable;

	var newWindow = window.open(address, 'Popup_Window', 'width=' + width + ',height=' + height + ',"' + features + '"');
	newWindow.focus();
}

function trim(s)
{
	// Remove leading spaces and carriage returns
	while (s.substring(0,1) == ' '){
		s = s.substring(1,s.length);
	}
	// Remove trailing spaces and carriage returns
	while (s.substring(s.length-1,s.length) == ' '){
		s = s.substring(0,s.length-1);
	}
	return s;
}

/*
$(function(){
	$("input[@type=text]").focus(function(){
		makeCurrent(this);
	});
	$("input[@type=text]").blur(function(){
		makeNormal(this);
	});
	$("textarea").focus(function(){
		makeCurrent(this);
	});
	$("textarea").blur(function(){
		makeNormal(this);
	});
});
*/

function makeCurrent(elem){
	$(elem).css("background-color", "white");
}
function makeNormal(elem){
	$(elem).css("background-color", "transparent");
}

/*************************
	Footer Javascript
*************************/

function callEmailSignup() {
	var userEmail = $("#subscribeEmail input[@name=userEmail]");
	
	if (userEmail.val() == 'your email address') {
		openWindow('/email_sign_up.jsp', 500, 550);
	} else {
		openWindow('/email_sign_up.jsp?userEmail=' + userEmail.val(), 500, 550);
		userEmail.val('your email address');
	}
	
	return false;
}

$(function(){
	$("#subscribeEmail input[@name=userEmail]").keydown(function(event) {
		if (event.keyCode == 13)
		{
			callEmailSignup();
			return false;
		}
	});

	$(".email-signup-contianer .signup-button").click(function(){
		callEmailSignup();
	});

	$(".email-signup-contianer .user-email").focus(function(){
		var userEmail = $(this).val();
		if (userEmail == "your email address"){
			$(this).val('');
		}
	});
	
	$(".email-signup-contianer .user-email").blur(function(){
		var userEmail = $(this).val();
		if (trim(userEmail) == ''){
			$(this).val("your email address");
		}
	});
});

/*
Recently Viewed left nav
this adds the elipsis and the hover effect for the recently viewed thumbnails below the left nav in catalog_nav
*/
var rvUtil = function($) {
	var timerID = null;
	var curr = null;
	var wrap = null;

	var abbrev = function(str) {
		if (str.length > 20)
			return str.substring(0,19) + "...";
		else
			return str;
	};

	var timerInit = function() {
		timerID = window.setTimeout("rvUtil.unhover()",200);
	};

	return {
		unhover : function() {
			$(".image img", wrap).css("opacity", 1);
			curr.empty();
		},

		init : function() {
			curr = $("#current-name");
			wrap = $("#rv-wrap");
			$(".image a", wrap).hover(
				function() {
					if (timerID != null)
						clearTimeout(timerID);
					curr.empty();
					$(".image img", wrap).css("opacity", 0.4);
					$(this).children("img").css("opacity", 1);
					var link = $(this).parent().parent().parent().find(".info > .name > a");
					$(link).clone().text(abbrev($(link).text())).appendTo(curr);
				},
				function() { timerInit(); }
			);
			curr.hover(
				function() {
					clearTimeout(timerID);
				},
				function() { timerInit(); }
			);
		}
	};
}($);

/*
highlights left nav items based on pageName
*/
function contentNavHighlighter() {
	var href = location.href;

	if (location.href.indexOf("pageName=") > -1) {
		var step1 = location.href.split("pageName=");
		var key = step1[1];

		if (key.indexOf("&") > -1) {
			//in case there are other attributes in the url
			//get only this one
			var step2 = key.split("&");
			key = step2[0];
		}
/*		if ($("#nav_" + key).parent().hasClass("thirdLevel")) {
		 	// in cases where we are on a subnav page, this sets the parent LI of the parent UL to on
			var parentKey = $("#nav_" + key).parent().parent().attr("id");
			if (parentKey != null)
				contentNavMakeActive(parentKey);
		}*/
	} else {
		if (location.href.indexOf(".jsp") > -1) {
			var step1 = location.href.split(".jsp");
		} else if (location.href.indexOf(".cmd") > -1) {
			var step1 = location.href.split(".cmd");
		}
		var step2 = step1[0].split("/");
		var key = step2[step2.length-1];
		//exceptions - these are needed when a form uses a command that's a different name than the original jsp
		if (key == "orderMaterials")
			key = "educational_materials";
		else if (key == "request_catalog_command")
			key = "request_catalog";
		else if (key == "contact_us")
			key = "contactus";
	}
	contentNavMakeActive("nav_" + key);	
}

function contentNavMakeActive(fullID) {
	$("#" + fullID + " > a").addClass("active"); //set the A to active
}


/*
The promo scroller method used on the homepage content area
*/
var promoScroller = function($) {
	var scrollerActiveIndex = 0; //the array position of the first element in full view
	var scrollerContentArr = new Array();
	var collLen = 0;
	var scrollerContentWidth = 0;
	var scrollerStartingX = 35;
	var enableAutoScroll = false;
	var isAnimating = false;
	var delay = 6000; // default delay in miliseconds
	var timerID = null;

	var timerInit = function() {
		timerID = window.setTimeout("promoScroller.autoScroll()", delay);
	};

	var lineup = function() {
		collLen = scrollerContentArr.length;
		var slide1 = scrollerContentArr[0];
		var slideLast = scrollerContentArr[collLen-1];
		slide1.css("left", scrollerStartingX + "px");
		slideLast.css("left", (scrollerStartingX - scrollerContentWidth) + "px");

		for (i=1; i<=scrollerContentArr.length-2 ;i++) {
			var slide = scrollerContentArr[i];
			var x = scrollerStartingX + (i * scrollerContentWidth);
			slide.css("left", x + "px");
		}
	};

	var done = function() { isAnimating = false; };

	var left = function() {
		if (isAnimating) return;
		if (enableAutoScroll) window.clearTimeout(timerID);

		isAnimating = true;
		//find the rightmost el and move it to the end on the left
		var currLeftIndex = scrollerActiveIndex == 0 ? collLen - 1 : scrollerActiveIndex - 1;
		var currRightIndex = currLeftIndex == 0 ? collLen - 1 : currLeftIndex - 1;
		var leftStartingX = parseInt(scrollerContentArr[currLeftIndex].css("left")) - scrollerContentWidth;

		for (var i=0; i<collLen; i++) {
			if (i == currRightIndex) {
				scrollerContentArr[i].css("left", leftStartingX + "px");
			}
			scrollerContentArr[i].animate({ "left":"+=" + scrollerContentWidth + "px" }, 350, null, done);
		}

		if (scrollerActiveIndex == 0)
			scrollerActiveIndex = (collLen - 1);
		else
			scrollerActiveIndex--;

		if (enableAutoScroll) timerInit();
	};

	var right = function() {
		if (isAnimating) return;
		if (enableAutoScroll) window.clearTimeout(timerID);

		isAnimating = true;
		//find the leftmost el and move it to the end on the right
		var currLeftIndex = scrollerActiveIndex == 0 ? collLen - 1 : scrollerActiveIndex - 1;
		var currRightIndex = currLeftIndex == 0 ? collLen - 1 : currLeftIndex - 1;
		var rightStartingX = parseInt(scrollerContentArr[currRightIndex].css("left")) + scrollerContentWidth;

		for (var i=0; i<collLen; i++) {
			if (i == currLeftIndex) {
				scrollerContentArr[i].css("left", rightStartingX + "px");
			}
			scrollerContentArr[i].animate({ "left":"-=" + scrollerContentWidth + "px" }, 350, null, done);
		}

		if (scrollerActiveIndex == (collLen - 1))
			scrollerActiveIndex = 0;
		else
			scrollerActiveIndex++;

		if (enableAutoScroll) timerInit();
	};

	var buildButtons = function() {
		$(".promoScroller-root").prepend(
				'<div class="promoScroller-left"><div class="positioner"><img src="/assets/images/btn/slider-left.png" class="ie6png" alt="scroll right" /></div></div>'
			);
		$(".promoScroller-root").append(
				'<div class="promoScroller-right"><div class="positioner"><img src="/assets/images/btn/slider-right.png" class="ie6png" alt="scroll left" /></div></div>'
			);
		$(".promoScroller-left").css("opacity",.8).click(right).hover(
				function() {
					$(this).css("opacity",0.3);
					//$("img",this).show();
				},
				function() {
					$(this).css("opacity",0.8);
					//$("img",this).hide();
				}
			);
		$(".promoScroller-right").css("opacity",.8).click(left).hover(
				function() {
					$(this).css("opacity",0.3);
					//$("img",this).show();
				},
				function() {
					$(this).css("opacity",0.8);
					//$("img",this).hide();
				}
			);
	};

	return {
		autoScroll : function() {
			right();
		},

		init : function(rootId,delayInSecs) {
			var parent = $("#"+rootId);

			if (parent.length > 0) {
				//if delay is not specified, used the default delay
				if (delayInSecs > 0) delay = delayInSecs * 1000;


				//find siblings and build array
				//scrollerContentWidth = testEl.width(); //set width for animations while we are here
				scrollerContentWidth = 330; //set width for animations while we are here
				$(".promoScroller-slide").each( function(i){
					scrollerContentArr.push($(this));
				} );

				//display and bind scrollers if necessary
				if (scrollerContentArr.length > 1) {
					buildButtons();
					lineup();
					if (enableAutoScroll) timerInit();
				}
			}
		}
	};
}($);


/*
The contentSlider method used on the homepage content area
*/
var contentSlider = function($) {
	var collection = null;
	var color = "#6d6861"; //set the default color here, always include the #

	var lineup = function() {

	};

	return {
		init : function(colorOverrideHex) {
			if (colorOverrideHex != null) {
				if (colorOverrideHex.indexOf("#")==-1)
					colorOverrideHex = "#" + colorOverrideHex; //add # in case it wasn't passed in
				color = colorOverrideHex;
			}
			$(".contentSlider-root").each( function(i){
				var downContent = $(this).find(".contentSlider-slide-down");
				var upContent = $(this).find(".contentSlider-slide-up");
				if (upContent.length > 0) {
					$(upContent).css("background-color", color).css("opacity",.85);
					$(upContent).css("bottom", "-"+$(upContent).height()+"px");
					$(this).bind("mouseenter", function() {
      				$(upContent).animate({ bottom: "+="+ $(upContent).height()}, 300);
					});
					$(this).bind("mouseleave", function() {
						$(upContent).animate({ bottom: "-="+ $(upContent).height()}, 300);
					});
				}
				if (downContent.length > 0) {
					$(downContent).css("background-color", color).css("opacity",.85);
					$(downContent).css("top", "-"+$(downContent).height()+"px");
					$(this).bind("mouseenter", function() {
						$(downContent).animate({ top: "+="+ $(downContent).height()}, 300);
					});
					$(this).bind("mouseleave", function() {
						$(downContent).animate({ top: "-="+ $(downContent).height()}, 300);
					});
				}
			});
		}
	};
}($);


/*
 * Get the total height of an object, including top and bottom padding and border
 *
 * @name     getTotalHeight
 * @author   Jim Scopacasa
 * @example  $("#someDiv").getTotalHeight();
 *
 */
jQuery.fn.getTotalHeight=function(o) {
    	return jQuery(this).height() + parseInt(jQuery(this).css("padding-bottom")) + parseInt(jQuery(this).css("padding-top")) + parseInt(jQuery(this).css("border-top-width")) + parseInt(jQuery(this).css("border-bottom-width"));
    };

/*
 * Selects a select menu option by value string, can call an error Handler if option is not found
 *
 * @name     selectOption
 * @author   Jim Scopacasa
 * @param    value: the value of the option you want to select
 				 ignoreCase: (optional), default is false, can set to true to ignore case when finding the value
 				 errorHandler: (optional), function to call if the option is not found
 * @example  $("#someSelect").selectOption("some value");
 *
 */
jQuery.fn.selectOption = function(value, ignoreCase, errorHandler) {
	this.each(
		function()	{
			if(this.nodeName.toLowerCase() != "select") return;
			var success = false;
			var optionsLength = this.options.length;
			for(var i = 0; i<optionsLength; i++) {
				var optValue = this.options[i].value;
				if (ignoreCase) {
					optValue = optValue.toLowerCase();
					value = value.toLowerCase();
				}
				if (optValue == value) {
					success = true;
					this.options[i].selected = true;
				};
			}
			if (!success && typeof errorHandler == 'function') {
				errorHandler(this, value);
			}
		}
	);
	return this;
};


jQuery.preloadImages = function() {
	var a = (typeof arguments[0] == 'object') ? arguments[0] : arguments;
	for(i=0; i < a.length; i++) {
		jQuery("<img>").attr("src", a[i]);
	}
};
