String.prototype.trim = function() {
	return this.replace( /^\s+|\s+$/, "" );
}
function removeCSSClass(elem, className) {
	elem.className = elem.className.replace(className, "").trim();
}
function addCSSClass(elem, className) {
	removeCSSClass(elem, className);
	elem.className = (elem.className + " " + className).trim();
}
function startList() {
	//createRollover("navShop");
	//createRollover("navMeta");
	//start for shopnav
	createRolloverForEach("nmjoin");
	createRolloverForEach("nmaboutmembership");
	createRolloverForEach("nmmymembership");
	createRolloverForEach("nmtravel");
	createRolloverForEach("nmservices");
	createRolloverForEach("nmrebates");
	createRolloverForEach("nmlocations");
	//start for shopnav
	createRolloverForEach("nselectronics");
	createRolloverForEach("nscomputers");
	createRolloverForEach("nshome");
	createRolloverForEach("nshealth");
	createRolloverForEach("nssports");
	createRolloverForEach("nsbaby");
	createRolloverForEach("nstoys");
	createRolloverForEach("nsjewelry");
	//New
    createRolloverForEach("nsofficesupplies");
    createRolloverForEach("nsseasonal");
	preloadNavs();
}
function preloadNavs(){
  pic1= new Image(100,25);
  pic1.src="/images/nav/join_now_on.gif";
  pic1.src="/images/nav/about_membership_on.gif";
  pic1.src="/images/nav/my_membership_on.gif";
  pic1.src="/images/nav/travel_on.gif";
  pic1.src="/images/nav/services_on.gif";
  pic1.src="/images/nav/rebates_on.gif";
  pic1.src="/images/nav/locations_on.gif";
  pic1.src="/images/nav/electronics_on.gif";
  pic1.src="/images/nav/computers_on.gif";
  pic1.src="/images/nav/home_on.gif"; 
  pic1.src="/images/nav/health_beauty_on.gif";
  pic1.src="/images/nav/sports_on.gif";
  pic1.src="/images/nav/baby_on.gif";
  pic1.src="/images/nav/toys_on.gif";
  pic1.src="/images/nav/jewelry_on.gif";
  pic1.src="/images/nav/office_supplies_on.gif";
  pic1.src="/images/nav/seasonal_on.gif";
}

var timeoutHolder;
var tempThis;
var lastTopItemOnClass;
var inTimingMode=false;
var alreadyShowingOneMenu=false;
function createRolloverForEach(id){
	var element=document.getElementById(id);
	if(element!==null){
		element.onmouseover=function() {
			//shows rollover state, not dropdown
			this.className=this.id+"over";
			clearTimeout(this.timeoutHolder);
			//show dropdown
			var subCatUl=this.getElementsByTagName('ul');
			if(subCatUl.length>0){

				subULInstance=subCatUl[0];
				subCatUl[0].onmouseover=function(){
						this.className=this.className;
				};
				this.timeoutHolder=setTimeout(function () {showDropdown();},"300");
				var subLiElements=subCatUl[0].getElementsByTagName("li");
				for(var i=0;i<subLiElements.length;i++){
					subLiElements[i].onmouseover=function(){
						clearTimeout(this.timeoutHolder);
						showDropdown();
					};
				}
				subLiElements[subLiElements.length-1].className="last";
			} else {
				clearAllMenus("navMeta");
				clearAllMenus("navShop");
			}

			//set iframe height
			//we need to set it here because we can only get offsetHeight when display!=none
			var iframeMat=element.getElementsByTagName('iframe');
			if(iframeMat.length>0){
				//iframeMat[0].style.height=(subCatUl[0].offsetHeight-3)+"px";
			}
		};

		element.onmouseout=function() {
			this.className=this.id;
			//hide dropdown

			var subCatUl=this.getElementsByTagName('ul');
			if(subCatUl.length>0){
				subULInstance=subCatUl[0];
				// clear the menu if it is pending
				clearTimeout(this.timeoutHolder);
				// shutdown the menu if it is open
				this.timeoutHolder=setTimeout(function() {hideDropdown(subCatUl[0])},"300");
			}
		};

		var subCatUl=element.getElementsByTagName('ul');
		if(subCatUl.length>0){
			//alert(subCatUl[0].offsetHeight);
			//insert iframe into the nav
			var ieLiContainer=document.createElement('li');
			var ieMat=document.createElement('iframe');
			ieMat.src="/images/nav/join_now.gif";
			ieMat.scrolling="no";
			ieLiContainer.style.border="none";
			ieMat.frameBorder="0";
			ieLiContainer.appendChild(ieMat);
			subCatUl[0].insertBefore(ieLiContainer, subCatUl[0].childNodes[0]);
		}
	}
}
var subULInstance;
function hideDropdown(element){
	element.className="";
	alreadyShowingOneMenu=false;
}
function showDropdown(){
	clearAllMenus("navMeta");
	clearAllMenus("navShop");
	subULInstance.className="over";
	alreadyShowingOneMenu=true;
	inTimingMode=false;
}

function startMouseOver(){
	addCSSClass(tempThis, "over");
}
function clearAllMenus(id){
	var uls=document.getElementById(id).getElementsByTagName("ul");
	for(i=0;i<uls.length;i++){
		uls[i].className="";
	}
}
/* start dropdown scripts */

var mouseOffTimer;
var originalWidth=0;
var menuBuilt=false;


//browser sniffing to load in dummy box
var bw = new lib_bwcheck();
function lib_bwcheck(){
	this.ver=navigator.appVersion;
	//this.vender = navigator.vender;
	this.product=navigator.product;
	this.moz= navigator.product == 'Gecko';
	this.agent=navigator.userAgent;
	this.dom=document.getElementById?1:0;
	this.mac=this.agent.indexOf("Mac")>-1;
	this.opera5=window.opera?1:0;
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0;
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie7=(this.ver.indexOf("MSIE 7")>-1 && this.dom && !this.opera5)?1:0;
	this.ie5mac=(this.ver.indexOf("MSIE 5.23")>-1 && !this.opera5 && this.mac)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6||this.ie7;
	this.saf=this.agent.indexOf("Safari")>-1;
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.moz||this.ie5mac||this.saf||this.ie7||this.ie6||this.ie5||this.ie4||this.ns4||this.ns6||this.opera5);
	return this;
}


/* Last Modified $Date: 11/07/07 11:17a $ by $Author: Rmulloy $ (Version history stored in Source Control) */

// set up browser detect vars
var isNS4 = (navigator.appName.indexOf("Netscape") != -1 && navigator.appVersion.charAt(0) == "4");
var isMOZ = (navigator.appName.indexOf("Netscape") != -1 && parseInt(navigator.appVersion.charAt(0)) >= 5);
var isIE = (navigator.appName.indexOf("Microsoft") != -1);

function openWindow(url, name, options) {
	var win = window.open(url,name,options);
    if (win != null) {
        win.focus();
    }
    return win;
}

function openSizedWindow(url, w, h, name) {
	if (!name) name = 'newWindow';
	var win = window.open(url,name,'toolbar=no,menubar=no,scrollbars=no,resizable=no,width=' + w + ',height=' + h);
    if (win != null) {
        win.focus();
    }
    return win;
}

function openReSizableWindow(url, w, h, name) {
	if (!name) name = 'newWindow';
	var win = window.open(url,name,'toolbar=no,menubar=no,resizable=yes,scrollbars=yes,width=' + w + ',height=' + h);
    if (win != null) {
        win.focus();
    }
    return win;
}

function openSizedWindowWithSB(url, w, h, name) {
	if (!name) name = 'newWindow';
	var win = window.open(url,name,'toolbar=no,menubar=no,resizable=no,scrollbars=yes,width=' + w + ',height=' + h);
    if (win != null) {
        win.focus();
    }
    return win;
}

function jumpTo(selectBox) {
	var url = selectBox.options[selectBox.selectedIndex].value;
	if (url != "") window.location.href = url;
}

function smWindow(url, name) {
    if (!name) name = 'newWindow';
    openReSizableWindow(url, 480, 220, name);
}

function openLocation(clubNumber) {
    openReSizableWindow('/locations/clubs/' + clubNumber + '.shtml', 500, 600, 'club' + clubNumber);
}

function gotoPartner(partnerURL) {
    var returnURL = escape(window.location);
    openSizedWindowWithSB('http://www.bjs.com/services/exit_pop.shtml?returnURL=' + returnURL, 480, 220, 'partnerWarning');
    return true;
}

function openFAQs(url, name) {
	return openReSizableWindow(url, 466, 490, name);
}

function pinShopNav(shopPin) {
	var shopNavElem = bgGetElementById(shopPin);
	if (shopNavElem != null) {
		shopNavElem.className = "pin";
	}
}

/**
 * This function returns a random number in the specified range
 *
 * @param	range- max integer value of the random number
 */
function pickRandom(range) {
	if (Math.random) {
		return Math.round(Math.random() * (range-1));
	}
	else {
		var now = new Date();
		return (now.getTime() / 1000) % range;
	}
}

/** Return the cookie value by its name. Returns null if no such cookie found.*/
function getCookie(cookieName)
{
	var results = document.cookie.match(cookieName + '=(.*?)(;|$)');

	if( results )
	{
		return (unescape(results[1]));
	}
  	else
  	{
    	return null;
    }
}

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=/";
}

/** find object on the page, by ID */
function bgGetElementById(id) {
	var elem = null;
	if (document.all) {
		elem = document.all[id];
	}
	else if (document.getElementById) {
		elem = document.getElementById(id);
	}
	return elem;
}


/** DEPRECATED FUNCTIONS **/

function deprecated() {
    alert("ERROR: The link you have clicked is using a deprecated function, please report this to the webmaster.");
}
function whatRewards() {
	deprecated();
}
function whatFHM() {
	deprecated();
}
function whatSupplemental() {
	deprecated();
}
function whatCID() {
	deprecated();
}
function changeName() {
    deprecated();
}
function showCategories(){
	createMenu();
	document.getElementById("categoryListDummy").style.display='block';
	document.getElementById("categoryList").blur();
	cleartimeout();
}
function hideCategoryList(){
	document.getElementById("categoryListDummy").style.display='none';
	//document.onkeydown = unregisterKeystrokes;
}
/* when the user selects an option things need to happen*/
function setFilters(listValue,liElement){
	//turn off div because option has been selected
	document.getElementById("categoryListDummy").style.display='none';
	ddElement=document.getElementById("categoryList");
	//need to unselect all to clear previously selected option
	unselectall();
	//set selected class for selected option
	liElement.className="selected";

	//sets original dropdown box value by adding an option to the list
	var option=new Option( liElement.innerHTML, listValue);
	ddElement.options[ddElement.options.length]=option;
	ddElement.value=listValue;

	var selectElement=document.getElementById("categoryList");
	var thisText="";
	for (i=0; i<selectElement.options.length; i++) {
		if(listValue==selectElement.options[i].value){
		  	thisText=selectElement.options[i].text;
		}
	}
	document.getElementById("selectText").innerHTML=thisText;

}
// removes all "selected" classnames from eveyr option
function unselectall(){
	ulElement=document.getElementById("categoryListDummy");
	for (i=0; i<ulElement.childNodes.length; i++) {
		ulElement.childNodes[i].className="";
	}
}
//programtically set some additional attributes for li elements
function setAttributes(){
	var ulElement=document.getElementById("categoryListDummy");
	var liElements=ulElement.getElementsByTagName("li");
	for (i=0; i<liElements.length; i++) {
		var liElement=liElements[i];
		liElement.onmouseout = function(){
          this.className="normal";
		  mouseOffTimer=setTimeout('hideCategoryList()',250)
        };
		liElement.onmouseover = function(){
          this.className="selected";
		  cleartimeout();
		  mouseOffTimer=setTimeout('hideCategoryList()',250);
        };
		liElement.onclick = function(){
          //need to find appropriate option in select box to get Value
			var selectElement=document.getElementById("categoryList");
			var thisValue=0;
			for (i=0; i<selectElement.options.length; i++) {
				if(this.innerHTML==selectElement.options[i].text){
			  		thisValue=selectElement.options[i].value;
				}
			}
			//we now have the value of the corresponding item
			setFilters(thisValue,this);

        };

	}
	ulElement.onmouseover = function(){
		  cleartimeout();
    };

	//one time set so we don't keep recreating the dropdown when the select box is clicked
	menuBuilt=true;
}
//creates the initial DHTML drop down menu based on the options for the standard <select> drop
function createMenu(){
	if(!menuBuilt){
		var selectElement=document.getElementById("categoryList");
		var ul=document.getElementById("categoryListDummy");
		for (i=0; i<selectElement.options.length; i++) {
			//don't show default value which is typically set to ""
			if(selectElement.options[i].value!=""){
				var li = document.createElement('li');
				var txt = document.createTextNode(selectElement.options[i].text);
				li.appendChild(txt);
				ul.appendChild(li);
			}
		}
		setAttributes();
	}
}
function cleartimeout(){
	clearTimeout(mouseOffTimer)
}
function registerKeystrokes(e){
	if (!e) e = window.event;
	//38=up arrow
	//40=down arrow
	//13=enter button
	if (e['keyCode']==38) {
		selectionAction("up");
		return false;
	}
	if (e['keyCode']==40) {
		selectionAction("down");
		return false;
	}
	if (e['keyCode']==13) {
		selectionAction("select");
		return false;
	}
}
function unregisterKeystrokes(e){
	//no need to do anything
}
//use the mouse cursor to select upwards
function selectionAction(action){
	var ulElement=document.getElementById("categoryListDummy");
	var liElements=ulElement.getElementsByTagName("li");
	var isAlreadySelected=false;
	var itemSelected=0;
	//need to check and see if there is already an option selected
	for (i=0; i<liElements.length; i++) {
		if(liElements[i].className=="selected"){
			isAlreadySelected=true;
			itemSelected=i;
		}
	}
	//if there is an object selected, then we need to move relatively from that element
	if(isAlreadySelected){
		//make sure not to go over the amount of items in list
		if(action=="up"){
			if(itemSelected>0){
				unselectall();
				liElements[itemSelected-1].className="selected";
			}
		} else if (action=="down"){
			if(itemSelected+1<liElements.length){
				unselectall();
				liElements[itemSelected+1].className="selected";
			}
		} else if (action=="select"){
			setSelectedValue(liElements[itemSelected]);
		}
	} else {
		//start at  first position
		if(action=="up"){
			liElements[liElements.length-1].className="selected";
		} else if (action=="down"){
			liElements[0].className="selected";
		}
	}
}
/* function to retrieve the value from the onclick attribute */
function setSelectedValue(listElement){
	var onclickValue=listElement.onclick;
	alert(onclickValue);
}

// passProfileValue(): used in SideCart and NewSearchBar
function passProfileValue(optID) {
  if (document.getElementById(optID) && document.getElementById('profilename')) {
    document.getElementById('profilename').value = document.getElementById(optID).innerHTML;
  }
}


/* #### FD SEARCH #### */
function fDSearch_go(ff) {
  f= ff.form;
  // fallback delimiters since vdev replaces | with /
  if( ff.value.indexOf(";") != -1 ) d=";";
  else if( ff.value.indexOf("|") != -1 ) d="|";
  else if( ff.value.indexOf("/") != -1 ) d="/";
  else d=";";
  pArr= ff.value.split(d);
  if( f.profile ) f.profile.value= pArr[0];
  if( f.profilename && pArr.length > 1 ) f.profilename.value= pArr[1];
}


function fDSearch_setSort(objOptionValue) {
  document.getElementById('pagesort').value = objOptionValue;
  document.fastSearchResultsForm.submit();
}

function fDSearch_setNewOffset(selIdx) {
  document.getElementById('offset').value = 0;
  //document.getElementById('path').value   = escape(document.getElementById('path').value);
  document.getElementById('offsethits').options.selectedIndex = selIdx;
  document.getElementById('fastSearchResultsFormSort').submit()
}

function fDSearch_setNewSort(ff) {
  //document.getElementById('path').value = escape(document.getElementById('path').value);
  // why?? ff.options.selectedIndex = selIdx;
  ff.form.submit()
}
/* Added by CW */
function mapPopup(product) {
  mapWindow = window.open("/mappopup.htm?productId="+product,"MapPopup","width=582,height=446");
}
