// some browser sniffing:
document.version = parseFloat(navigator.appVersion);
document.hostApplication = navigator.appName.substring(0, 3);
document.browserClass = parseInt(document.version);

var timeOn = null;
numMenus = 7;

//prevent js errors from showing (doesn't work in IE)
window.onerror = null;

// initialize hacks whenever the page loads
window.onload = initializeHacks;

//define global toProperCase function
String.prototype.toProperCase = function() {
	return this.toLowerCase().replace(/^(.)|\s(.)/g,
      function($1) { return $1.toUpperCase(); });
}
//function to remove non-numeric chars from an input, i.e. an element id since id's cannot begin with a number
function StripNonNumeric(input) {
	return input.replace(/[^0-9]/g, '');
}

// SET BACKGROUND COLOR 
function getImage(name) {
	if (document.layers)
		return findImage(name, document);
	return null;
}

function findImage(name, doc) {
	var i, img;
	for (i = 0; i < doc.images.length; i++)
		if (doc.images[i].name == name)
		return doc.images[i];
	for (i = 0; i < doc.layers.length; i++)
		if ((img = findImage(name, doc.layers[i].document)) != null) {
		img.container = doc.layers[i];
		return img;
	}
	return null;
}

function getImagePageLeft(img) {
	var x, obj;
	if (document.layers) {
		if (img.container != null)
			return img.container.pageX + img.x;
		else
			return img.x;
	}
	return -1;
}

function getImagePageTop(img) {
	var y, obj;
	if (document.layers) {
		if (img.container != null)
			return img.container.pageY + img.y;
		else
			return img.y;
	}
	return -1;
}

// ***********************
// hacks and workarounds *
// ***********************

// setup an event handler to hide popups for generic clicks on the document
function initializeHacks() {
	// this ugly little hack resizes a blank div to make sure you can click
	// anywhere in the window for Mac MSIE 5
	if ((navigator.appVersion.indexOf('MSIE 5') != -1)
		&& (navigator.platform.indexOf('Mac') != -1)
		&& getStyleObject('blankDiv')) {
		window.onresize = explorerMacResizeFix;
	}
	resizeBlankDiv();
	// this next function creates a placeholder object for older browsers
	createFakeEventObj();
}

function createFakeEventObj() {
	// create a fake event object for older browsers to avoid errors in function call
	// when we need to pass the event object to functions
	if (!window.event) {
		window.event = false;
	}
}

function resizeBlankDiv() {
	// resize blank placeholder div so IE 5 on mac will get all clicks in window
	if ((navigator.appVersion.indexOf('MSIE 5') != -1)
	&& (navigator.platform.indexOf('Mac') != -1)
	&& getStyleObject('blankDiv')) {
		getStyleObject('blankDiv').width = document.body.clientWidth - 20;
		getStyleObject('blankDiv').height = document.body.clientHeight - 20;
	}
}

function explorerMacResizeFix() {
	location.reload(false);
}

/*function mClk(src){ 
if(event.srcElement.tagName=='TD')
src.children.tags('A')[0].click();
}*/

// prevent two checkboxes from being checked at the same time
function exclusiveCheckBox(arBoxGroup, arBoxGroupName) {
	for (var i = 0; i < arBoxGroup.length; i++) {
		if (arBoxGroup[i].checked) {
			if (confirm('This box cannot be checked while ' + arBoxGroupName[i] + ' is checked.\nClick OK to uncheck the ' + arBoxGroupName[i] + ' box and check this box.\nOtherwise, click CANCEL.')) {
				arBoxGroup[i].checked = false;
				return true;
			} else {
				return false;
			}
		}
	}
}
//get the value of a parameters from the query string
function getQueryParam(name) {
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var tmpURL = window.location.href;
	var results = regex.exec(tmpURL);
	if (results == null)
		return "";
	else
		return results[1];
}

//removes a parameter from a specified url
function RemoveParameterFromUrl(url, parameter) {
	var urlparts = url.split('?');

	if (urlparts.length >= 2) {
		var prefix = encodeURIComponent(parameter) + '=';
		var pars = urlparts[1].split(/[&;]/g);
		for (var i = pars.length; i-- > 0; )
			if (pars[i].lastIndexOf(prefix, 0) !== -1)
			pars.splice(i, 1);
		url = urlparts[0];
		if (pars.length > 0)
			url += '?' + pars.join('&');
	}

	return url;
}


//get the value of a cookie by name
function getCookieValue(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;
}

/*get the value of a cookie by 
name - cookie name
value - value to set
expire days - number of days after which this should expire
*/
function setCookieValue(name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = name + "=" + value + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
}

//- for auto date footer;
today = new Date();
var y0 = today.getFullYear();

/*
filterResults supports att filtering on result sets used in search results, and any product results
*/
function filterResults(filter, initialHits) {
	var newLocation = window.location.toString();
	if (filter != null) newLocation = replaceQueryParam(newLocation, 'filter', filter);
	newLocation = replaceQueryParam(newLocation, 'processor', 'content');
	newLocation = replaceQueryParam(newLocation, 'pg', '1');
	if (initialHits != null) newLocation = replaceQueryParam(newLocation, 'p_initialhits', initialHits);
	window.location = newLocation;
	return true;
}

/*
showAllResults supports showing all results in search results, and any product results
*/
function showAllResults(totalResults) {
	var newLocation = window.location.toString();
	newLocation = replaceQueryParam(newLocation, 'processor', 'content');
	newLocation = replaceQueryParam(newLocation, 'pg', '0');
	if (totalResults != null) newLocation = replaceQueryParam(newLocation, 'ps', totalResults);
	window.location = newLocation;
	return true;
}

/*
replaceQueryParam finds and replaces a query string parameter in a url
*/
function replaceQueryParam(url, param, value) {
	var delim = '&'; if (url.indexOf('?') == -1) delim = '?';
	var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");

	if (url.match(re))
		return url.replace(re, '$1' + param + "=" + value + '$2');
	else
		return url + delim + param + "=" + value;
}
function continueShopping(prevUrl) {
	if (document.referrer.indexOf('default.asp') > 0 || document.referrer.indexOf('cart.aspx') > 0)
		prevUrl = '/store/home.aspx';
	window.location = prevUrl;

	return true;
}
//apends the key/value to the end of a query string of a given anchor tag
function QueryStringAppend(anchor, value, name) {
	var url = $(anchor).attr('href');
	//check if contains query string ('?'), check also for only '?'
	var delim = (url.indexOf('?') == -1) ? '?' : ((url.substr(-1) === '?') ? '' : '&');
	if (url.indexOf(name) == -1)
		$(anchor).attr('href', url + delim + name + '=' + value);
}
//for results paging
function populateDropdowns(form, currentperpage, currentpage, totalresults, ppfrom, ppstep, ppto, pplist) {
	var lst2 = form.pg;
	if (lst2 != null) {
		for (i = lst2.length; i >= 1; i--) {
			lst2.options[i] = null;
		}
		lst2.options.length = 1;
		index = 2;
		pages = totalresults / currentperpage - 1;
		for (i = 0; i < pages; i++) {
			var opt = document.createElement('option');
			opt.value = index;
			opt.text = index;
			lst2.options[index - 1] = opt;
			if ((currentpage > 0) && (index == currentpage)) {
				lst2.options[index - 1].selected = true;
			}
			index = index + 1;
		}
	}
	var lst = form.pp;
	if (lst != null) {
		if (ppfrom != '' && ppstep != '' && ppto != '') {
			var val;
			var index, i;
			i = 0;
			for (val = ppfrom; val <= ppto; val = val + ppstep) {
				var opt = document.createElement('option');
				opt.value = val;
				opt.text = val;
				lst.options[i] = opt;
				if (val == currentperpage) {
					lst.options[i].selected = true;
				}
				i++;
			}
		} else {
			var pparray = pplist.split('|');
			var num = pparray.length;
			var i;
			var val;
			for (i = 0; i < num; i++) {
				var opt = document.createElement('option');
				if (pparray[i] == 'All') {
					val = totalresults;
				}
				else {
					val = pparray[i];
				}
				opt.value = val;
				opt.text = pparray[i];
				lst.options[i] = opt;
				if (val == currentperpage)
					lst.options[i].selected = true;
			}
		}
	}
}

function clearCustomer(token) {
	var url = '/default.asp?processor=asp&asp_processor=store&action=logout&t=' + token;
	$.ajax({
		'url': url,
		'type': 'get',
		'dataType': 'text',
		'complete': function(data) {
			$('#customer_welcome').html('');
			window.location.href = '/store/dtc-shared/myaccountlogin/myaccountlogin.aspx';
		}
	});
}

/*dynamic item pricing routines*/
var itemList = '';
var itemText = new Array("SALE", "NEW!", "WEB ONLY", "SPECIAL", "IMPROVED", "LIMITED QTY", "LOWER PRICE", "SALE", "BUY 2 &amp; SAVE", "BUY 3 &amp; SAVE", "BUY 4 &amp; SAVE", "WEB ONLY SALE", "NEW COLOR");

function wireupPrices() {
	$('div.price-item').each(function(n, div) {
		var item = $(div).attr('id');
		item = item.replace('item-price-', '');
		itemList += item + ',';
	});
	itemList = itemList.slice(0, -1);
	if (itemList.length > 0)
		$.getJSON('/services/ecom.price.lookup.ashx?style_cd=' + itemList, function(data) {
			processPricingData(data);
		});
}

function processPricingData(data) {
	var len = data.priceLookup.length;
	for (var i = 0; i < len; i++) {
		var item = data.priceLookup[i];
		var pdiv = $('#item-price-' + item.stylecd);
		if (pdiv != undefined) {
			pdiv.html(renderProductPrice(item));
		}
	}
	$('#price-items').show();
}

function renderProductPrice(itemJSON) {
	var item = itemJSON;
	var text = ''; var itemMessage = '';
	if (Number(item.price) < Number(item.wasprice)) item.itemtype = '1';
	text = '<p class="price">';
	if (Number(item.price) < Number(item.wasprice)) {
		text += '<span class="item-wasprice">$' + item.wasprice + '</span>';
		text += '<span class="item-price-sale"> $' + item.price + '</span>';
	} else {
		text += '<span class="item-price">$' + item.price + '</span>';
	}
	text += '</p>';
	return text;
}

//p=product json
function writeProductSummary(p, i, h, w, pt, ev3) {
	if (isNaN(parseInt(h))) h = 115;
	if (isNaN(parseInt(w))) w = 115;
	var idPrefix;
	switch (pt) {
		case 'rv':
			idPrefix = 'rv';
			if (!ev3) ev3 = 'recently-viewed';
			break;
		case 'rp':
			idPrefix = 'rp';
			if (!ev3) ev3 = 'recommended_products';
			break;
		case 'cms':
			idPrefix = 'cms';
			if (!ev3) ev3 = 'recommended_home';
			break;
	}
	var html = '<div class="itembox" id="' + idPrefix + p.stylecd + '">';
	//default to sale type if price < was
	if (Number(p.price) < Number(p.wasprice))
		p.itemtype = 1;
	//check for item type flag
	if (parseInt(p.itemtype) > 0) {
		html += '<a class="flag ' + itemText[p.itemtype - 1].replace(/(&amp;| |&|!)*/gi, '').toLowerCase() + '" href="' + p.url + '"><div><div>' + itemText[p.itemtype - 1] + '</div></div></a>';
	}
	html += GetProductViewLink(ev3, p.url, 'image', '<div class="shadow"></div>' + GetProductImage(h, w, p.title, p.img)) +
        '<h5>' + GetProductViewLink(ev3, p.url, '', p.title) + '</h5>' +
        renderProductPrice(p);
	//if (pt == 'rp' || pt == 'cms') html += renderProductRating(p);
	if (pt == 'rv')
		html += '<div class="item-options"><a href="#" rel="nofollow" onClick="acuCustomer.vpRemove(\'' + p.stylecd + '\'); return false;">Remove</a></div>';
	html += '</div>';
	return html;
}
function writeProductSummaryList(p, i, h, w, pt, ev3) {
	if (isNaN(parseInt(h))) h = 115;
	if (isNaN(parseInt(w))) w = 115;
	var idPrefix;
	switch (pt) {
		case 'rv':
			idPrefix = 'rv';
			if (!ev3) ev3 = 'recently-viewed';
			break;
		case 'rp':
			idPrefix = 'rp';
			if (!ev3) ev3 = 'recommended_products';
			break;
		case 'cms':
			idPrefix = 'cms';
			if (!ev3) ev3 = 'recommended_home';
			break;
	}
	var html = '<tr id="' + idPrefix + p.stylecd + '"><td class="image">' + GetProductImage(h, w, p.title, p.img) + '</td>' +
               '<td class="description"><h5>' + p.title + '</h5><p class="itemnumber">Item: ' + p.stylecd + '</p></td>' +
               '<td class="unitcost">' + renderProductPrice(p) + '</td>';
	if (pt == 'rv')
		html += '<td class="remove"><a href="#" class="remove" rel="nofollow" onClick="acuCustomer.vpRemove(\'' + p.stylecd + '\'); HandleAlertMessage(\'<strong>Success!</strong><span> The item has been removed.</span>\', \'user-message\', \'success\'); return false;"><div></div>Remove Item</a></td>';

	html += '<td class="actions">' + GetProductViewLink(ev3, p.url, 'btn secondary go', '<div></div><span>View Item</span>') + '</td></tr>';
	return html;
}
function GetProductImage(h, w, title, imgSrc) {
	return '<img width="' + w + '" height="' + h + '" border="0" alt="Picture of ' + title + '" src="' + acuMediaImageSrc.GetImageSrc(imgSrc, h, w) + '"/>';
}
function GetProductViewLink(ev3, url, cssClass, innerhtml) {
	return '<a ' + (cssClass ? 'class="' + cssClass + '"' : '') + ' rel="nofollow" onclick="QueryStringAppend(this,\'' + ev3 + '\',\'ev3\');" href="' + url + '">' + innerhtml + '</a>';
}

function renderProductRating(p) {
	var ratingSnippet = '';
	if (p.rtCount >= 3)
		ratingSnippet = '<div class="pr_snippet_category">' +
		'<div class="pr_snippet" id="pr_' + p.stylecd + '">' +
		'<div class="pr_snippet_rating_unclickable">' +
		'<div class="pr_stars" style="background-position: 0px -' + Math.round((p.rtAvg - 0.01) / 0.5) * 18 + 'px;"></div>' +
		'<div class="pr_snippet_number_ratings_text"> (' + p.rtCount + ' Ratings)</div>' +
		'</div></div></div>';
	return ratingSnippet;
}
//was: function renderProducts(items, t, h, w, pt, limit, ev3, layout, visibleItems) {
function renderProducts(props) {
	$.getJSON('/services/ecom.price.lookup.ashx?style_cd=' + props.items.join(','), function(data) {
		//was: renderProductData(data, t, h, w, pt, limit, ev3, layout);
		renderProductData(data, props);
	});
}
//was: function renderCategoryProducts(catName, t, h, w, pt, limit, ev3, layout, visibleItems) {
function renderCategoryProducts(props) {
	$.getJSON('/services/ecom.price.lookup.ashx?cat_name=' + props.catName, function(data) {
		//was: renderProductData(data, props.target, props.height, props.width, props.pt, props.limit, props.ev3, layout);
		renderProductData(data, props);
	});
}
//was: function renderUpsellProducts(postJson, t) {
function renderUpsellProducts(props) {
	$.getJSON('/services/ecom.price.lookup.ashx?product_upsell=1&style_cd=' + props.sku_1 + '&cid=' + props.cartid + '&edp=' + props.edp_1, function(data) {
		UpdateProductCartSummary(props, data.cartSummary);
		//dynamic mobox check (created with mboxDefine()), target element should have name property set
		if (typeof mboxUpdate == "function" && props.target.data('name') != '') {
			mboxUpdate(props.target.data('name'));
		} else {
			props.pt = 'rp';
			renderProductData(data, props);
		}
	});
}
//was: function renderProductData(json, t, h, w, pt, limit, ev3, layout, visibleItems) {
function renderProductData(json, props) {
	var t = $(props.target);
	var l;
	if (props.limit == undefined)
		props.limit = 99;
	if (props.limit > json.priceLookup.length)
		l = json.priceLookup.length;
	else
		l = props.limit;
	for (var i = 0; i < l; i++) {
		if (props.layout == 'listview')
			t.append(writeProductSummaryList(json.priceLookup[i], i, props.height, props.width, props.pt, props.ev3));
		else
			t.append(writeProductSummary(json.priceLookup[i], i, props.height, props.width, props.pt, props.ev3));
	}
	if (!props.visibleItems) props.visibleItems = 6;
	//check for more than 6 results and a parent scrollable class
	if (t.parent().hasClass("scrollable")) {
		initScrollable(t.parent(), l, props.visibleItems);
	}
}

function initScrollable(target, itemCount, visibleItems) {
	//if this is a scrollable element, check that the number of items exceeds the number of possible visible items
	//otherwise hide the navigation button
	if (itemCount > visibleItems) {
		//make sure dom is ready
		$(function() {
			//set custom visibleItems property for onBeforeSeek function
			target.scrollable({
				'speed': 200,
				'keyboard': false,
				'visibleItems': visibleItems,
				'onBeforeSeek': function(event, idx) {
					//if we've reached the end of the visible items, hide the next button, otherwise show
					var dif = (this.getSize() - this.getConf().visibleItems) - idx;
					if (dif <= 0) { $(this.getNaviButtons()[1]).hide(); }
					else { $(this.getNaviButtons()[1]).show(); }
				}
			});
		});
	} else {
		target.siblings('a.prev, a.next').hide();
	}
}

var acuCustomer = new function() {
	this.displayName = '';
	this.cartId = '';
	this.customerId = '';
	this.isLoggedIn = false;
	this.vp = Array();
	this.viewProduct = function(prodId) {
		this.vpLoad();
		for (var i = 0; i < this.vp.length; i++) {
			if (prodId == this.vp[i])
			{ this.vp.splice(i, 1); break; }
		}
		this.vp.push(prodId);
		if (this.vp.length > 10)
			this.vp.shift();
		this.vpSave();
	}
	this.viewedProducts = function() {
		if (this.vp.length > 0)
			return this.vp.join(',');
	}
	this.vpSave = function() {
		if (this.vp.length > 0)
			setCookieValue('ac-vp', this.viewedProducts(), 90);
	}
	this.vpLoad = function() {
		var vpC = getCookieValue('ac-vp');
		if (vpC != null && vpC != 'off')
			this.vp = vpC.split(',');
	}
	this.vpRemove = function(id) {
		this.vpLoad();
		for (var i = 0; i < this.vp.length; i++) {
			if (id == this.vp[i])
			{ this.vp.splice(i, 1); break; }
		}
		this.vpSave();
		var item = $('#rv' + id);
		if (item) { item.hide(); item.remove(); }
	}
	this.vpClearAll = function() {
		setCookieValue('ac-vp', '', -1);
	}
	this.vpDisable = function() {
		setCookieValue('ac-vp', 'off', 365);
	}
	this.renderViewedProducts = function(target, count, h, w, pt, ev3, layout) {
		if (!pt) pt = 'rv';
		if (!layout) layout = 'gridview';
		var cookie = getCookieValue('ac-vp');
		if (cookie) {
			var p = cookie.split(',').reverse();
			if (p != null) {
				if (p.length > count) {
					p = p.slice(0, count);
				}
				//was: renderProducts(p, target, h, w, pt, null, ev3, layout);
				renderProducts({
					'items': p,
					'target': target,
					'height': h,
					'width': w,
					'pt': pt,
					'limit': null,
					'ev3': ev3,
					'layout': layout,
					'visibleItems': 6
				});
			}
			$(document).ready(function() {
				var products = $('div.product-summary[name^="rv"]');
				if (pt == 'rp') {
					if ($('#category_recently_viewed') && cookie != 'off' && cookie != '') {
						$('#recently_viewed_header').append('<a href="" rel="nofollow" onclick="GotoRecentlyViewed(); return false;" class="goto_recently_viewed">See more</a><h2>-</h2>');
					}
				} else if (products.length > 0) {
					products.last().after('<a href="" rel="nofollow" onclick="GotoRecentlyViewed(); return false;" class="goto_recently_viewed">More Recently Viewed Items</a>');
				}
			});
			$(target).show();
		}
	}
	this.renderProductsCMS = function(prodIdList, h, w, limit, custClass, ev3) {
		if (prodIdList) {
			var id = (new Date()).getTime();
			document.write('<div id="' + id + '"></div>');
			var target = $('#' + id).closest('div.complexlinkfloat').get(0);
			if (custClass) $(target).addClass(custClass);
			$(target).children('div').hide();
			if (!limit) limit == 5;
			//was: renderProducts(prodIdList.split(','), target, h, w, 'cms', limit, ev3);
			renderProducts({
				'items': prodIdList.split(','),
				'target': target,
				'height': h,
				'width': w,
				'pt': 'cms',
				'limit': limit,
				'ev3': ev3,
				'visibleItems': 6
			});
			$(target).show();
		}
	}
	this.renderRecommendedProducts = function(target, prodIds, count, h, w, ev3, tabname) {
		if (prodIds) {
			//if no target found, fall out.
			if (!target || target.length == 0) return;
			//split product id list on ','
			var p = prodIds.split(',');
			//validate count to display, fall back to 4
			if (!count || isNaN(count)) count = 4;
			//hide any empty divs in the target div
			$(target).hide().empty();
			//call to render products
			//was: renderProducts(p, target, h, w, 'rp', count, ev3);
			renderProducts({
				'items': p,
				'target': target,
				'height': h,
				'width': w,
				'pt': 'rp',
				'limit': count,
				'ev3': ev3,
				'visibleItems': 6
			});
			//for carousel tabs, call to override the tab name if one is provided
			if (tabname && $.trim(tabname) != '')
				$('div.carouseltabs ul.tabs a[href="#' + target.attr('id').replace('-upsell', '') + '"] span').text(tabname);
			//show the target container
			$(target).show();
		}
	}
	this.renderRecommendedCategoryProducts = function(target, catName, count, h, w, ev3, tabname) {
		if (catName) {
			if (!count || isNaN(count)) count = 4;
			renderCategoryProducts({
				'catName': catName,
				'target': target,
				'height': h,
				'width': w,
				'pt': 'rp',
				'limit': count,
				'ev3': ev3,
				'visibleItems': 6
			});
			if (tabname && $.trim(tabname) != '')
				$('div.carouseltabs ul.tabs a[href="#' + target.attr('id').replace('-upsell', '') + '"] span').text(tabname);
			$(target).show();
		}
	}
	this.forgotPassword = function(token, email) {
		if (email == '' || email == undefined)
			HandleAlertMessage('Please enter your email address.  Your password will be emailed to that address.', 'user-message', 'notice');
		else
			$.ajax({
				'url': '/default.asp?processor=asp&asp_processor=wishlist&action=passwordreminder',
				'type': 'post',
				'dataType': 'xml',
				'data': { 'rngn': 'xml', 'e': email, 't': token },
				'success': function(xml) { acuCustomer.forgotPasswordComplete(xml, email); }
			});
	}
	this.forgotPasswordComplete = function(xml, e) {
		var errors = xml.getElementsByTagName('error');
		if (errors.length == 0)
			HandleAlertMessage('Your password has been sent to ' + e, 'user-message', 'success');
		else
			this.alertUserErrors(errors);
	}
	this.alertUserErrors = function(errors) {
		var sMessage = '';
		for (var i = 0; i < errors.length; i++)
			sMessage += errors[i].childNodes[0].nodeValue + '\n';
		HandleAlertMessage(sMessage, 'user-message', 'alert');
	}
}
// expand/collapse toggle switch for divs
function ExpandCollapseDiv(override) {
	if (override == null) {
		$('#filter').find('select').each(function(idx, s) {
			if (s.selectedIndex > 0)
				override = true;
		});
	}
	var toggle = $('#filter_toggle');
	var html = toggle.html();
	var filters = $('#filter').find('div');
	var l = filters.length;
	if (l > 4) {
		toggle.css('display', 'inline');
		if (html == 'More filters' || override) {
			toggle.html('Fewer filters');
			for (i = 4; i < l; i++) {
				filters[i].attr('class', 'attribute');
			}
		} else {
			toggle.html('More filters');
			for (i = 4; i < l; i++) {
				filters[i].attr('class', 'attributeMin');
			}
		}
	} else {
		toggle.css('display', 'none');
	}
}
function DisplayFlashContent() {
	$('div.complexlinkfloat').find('div.flash').each(function(elem) {
		DisplayFlash(this.flash);
	});
}
//EOLAS IE flash workaround
function DisplayFlash(elemJSON) {
	var strFlash = '';
	strFlash += '<object classid="' + elemJSON.classid + '" codebase="' + elemJSON.codebase + '" id="' + elemJSON.contentid + '"';
	if (elemJSON.width > 0)
		strFlash += ' width="' + elemJSON.width + '"';
	if (elemJSON.height > 0)
		strFlash += ' height="' + elemJSON.height + '"';
	strFlash += '">';
	strFlash += '<param name="movie" value="' + elemJSON.source + '">';
	strFlash += '<param name="quality" value="' + elemJSON.quality + '">';
	strFlash += '<param name="play" value="' + elemJSON.autoplay + '" / >';
	strFlash += '<param name="wmode" value="transparent" / >';
	strFlash += '<param name="flashvars" value="' + elemJSON.params + '" />';
	strFlash += '<embed src="' + elemJSON.source + '" quality="' + elemJSON.quality + '" pluginspage="' + elemJSON.pluginspage + '" type="application/x-shockwave-flash" name="' + elemJSON.contentid + '"';
	if (elemJSON.width > 0) {
		strFlash += ' width="' + elemJSON.width + '"';
	}
	if (elemJSON.height > 0) {
		strFlash += ' height="' + elemJSON.height + '"';
	}
	strFlash += ' play="' + elemJSON.autoplay + '" loop="' + elemJSON.loop + '" autostart="' + elemJSON.autoplay + '" flashvars="' + elemJSON.params + '" wmode="transparent"';
	strFlash += '</embed>';
	strFlash += '</object>';
	$('#flash_' + elemJSON.contentid).html(strFlash);
}
function GetRadioIntValue(radioList) {
	var ret = -1;
	var l = radioList.length;
	for (var i = 0; i < l; i++) {
		if (radioList[i].checked) {
			ret = radioList[i].value;
		}
	}
	return parseInt(ret);
}
//todo: only grabs logged in users address books if page is in ssl
function GetAddressBookList(select, token, cid) {
	if (!select.updated) {
		var url = '/store/home.aspx';
		var params = {
			processor: 'asp',
			'asp_processor': 'ecom',
			action: 'addressbook_list',
			rngn: 'xml',
			t: token,
			cart_id: cid
		};
		var callback = function(data) {
			UpdateOptionsList(data, select.get(0));
		}
		DoRequest(url, params, 'POST', callback, false, 'xml');
	}
}

function UpdateOptionsList(data, select) {
	if (select && select.options) {
		var addresses = data.getElementsByTagName("addressbook");
		if (addresses) {
			select.options.length = 0;
			$(addresses).each(function(idx, node) {
				var option = document.createElement("option");
				option.value = node.attributes[0].value;
				option.text = node.attributes[0].value;
				select.options[idx] = option;
			});
		}
		if (select.options.length > 1)
			select.updated = true;
	}
}

function DoRequest(url, params, m, callback, ssl, datatype) {
	if (!m) m = 'POST';
	if (!ssl) ssl = false;
	url = (ssl ? 'https://' : (window.location.protocol + '//')) + window.location.hostname + url;
	$.ajax({
		'url': url,
		'type': m,
		'data': params,
		'dataType': datatype,
		'success': callback
	});
}

/******************************************/
/********BEGIN MBOX CART FUNCTIONS*********/
/******************************************/
function ShowCalcShipping() {
	$('#estimate_shipping').show();
}
function ShowRecentlyViewed() {
	$('#cart_recently_viewed').show();
	$('#cart_upselltable').removeClass('four_col');
	//check for xsl rendered products, only keep first two
	var tds = $('#cart_upselltable').find('td[width="130"]');
	if (tds && tds.length > 2) {
		for (var i = 2; i < tds.length; i++) {
			$(tds[i]).remove();
		}
	}
	//check for js dynamic rendered products, only keep first two
	var divs = $('#cart_upselltable').find('div.product-summary');
	if (divs && divs.length > 2) {
		for (var i = 0; i < divs.length; i++) {
			if (i > 1)
				$(divs[i]).remove();
			else
				$(divs[i]).css('margin', 0);
		}
	}
}
function ShowGlobalRecentlyViewed() {
	acuCustomer.renderViewedProducts($('#category_recently_viewed'), 10, 105, 105, 'rp', 'recently-viewed');
}
function CollapseFilters() {
	ExpandCollapseDiv(null);
}
function ShowMcafee() {
	$('#mcafee_trust_mark').show();
	$('#mcafee_trust_mark').html('<a target="_blank" href="https://www.mcafeesecure.com/RatingVerify?ref=www.duluthtrading.com">' +
   '<img width="115" height="32" border="0" src="//images.scanalert.com/meter/www.duluthtrading.com/12.gif"' +
   'alt="McAfee SECURE sites help keep you safe from identity theft, credit card fraud, spyware, spam, viruses and online scams"' +
   'oncontextmenu="alert(\'Copying Prohibited by Law - McAfee Secure is a Trademark of McAfee, Inc.\'); return false;"/></a>');
}
function ShowCheckoutFormB() {
	$('#checkout_form_a').hide();
	$('#checkout_form_b').show();
}
/******************************************/
/********END MBOX CART FUNCTIONS*********/
/******************************************/

function doFormSubmit(theForm) {
	if (theForm.onsubmit != undefined) {
		if (theForm.onsubmit())
			theForm.submit();
	}
	else theForm.submit();
}
function limitText(f, l, d) {
	var element = $(f);
	if (d == null)
		d = false;
	var ln = element.val().length;
	if (ln > l)
		element.val() = element.val().substring(0, l);
	if (d) {
		if (document.getElementById(element.attr('id') + '_counter')) {
			$(element.attr('id') + '_counter').html(element.val().length + " / " + l);
		} else {
			var t = new Element('span', { 'id': element.attr('id') + '_counter' });
			$(t).html(element.val().length + " / " + l);
			element.append(t);
		}
	}
}
function BindFloatingContentAnchors() {
	$('div.complexlinkfloat').each(function(x, d) {
		$(this).find('a:not([class~="popup"])').filter(':not([class~="notrack"])').bind('click', { 'div': d }, function(e) {
			var a = $(this);
			var h = a.attr('href');
			if (h.indexOf('feature=') == -1 && h.indexOf('javascript:') == -1 && h.indexOf('mailto:') == -1 && h.indexOf('http:') == -1) {
				var querystring = (a.attr('id') == '' ? $(e.data.div).attr('id') + 'L4' : a.attr('id'));
				QueryStringAppend(this, querystring, 'feature');
			}
		});
	});
}
function BindMarqueeAnchors() {
	$('div[class^="complexlink_body"]').find('a').addClass('L4');
	$('div.slide').each(function(idx, d) {
		$(this).find('a:not([class~="popup"])').filter(':not([class~="notrack"])').bind('click', { 'div': d }, function(e) {
			var a = $(this);
			var h = a.attr('href');
			if (h.indexOf('feature=') != -1) {
				h = h.replace(/(feature=\s*complex_link_\d{0,2}&?)/i, '');
				a.attr('href', h);
			}
			if (h.indexOf('javascript:') == -1 && h.indexOf('mailto:') == -1 && h.indexOf('http:') == -1) {
				var querystring = $(e.data.div).attr('id') + (a.hasClass('L4') ? 'L4' : 'L2');
				QueryStringAppend(this, querystring, 'feature');
			}
		});
	});
}
function ApplyOfferCode(code, t, a) {
	var url = document.location.protocol + '//' + window.location.host + '/default.asp';
	var params = {
		'processor': 'asp',
		'asp_processor': 'store',
		'action': 'applyoffercode',
		'rngn': 'xml',
		'catalog_number': code,
		't': t
	};
	var callback = function(xml) {
		var errorArray = [];
		$(xml).find('user_errors error').each(function(idx) {
			errorArray[errorArray.length] = $(this).text();
		});
		if (errorArray.length > 0) {
			var errorHtml = '';
			for (var i = 0; i < errorArray.length; i++) {
				errorHtml += errorArray[i] + '<br/>';
			}
			HandleAlertMessage(errorHtml, 'offer-message', 'alert');
		} else {
			if ($(xml).find('offerdesc').length > 0) {
				if ($(xml).find('offerdesc').attr('offer_desc'))
					HandleAlertMessage('<strong>Special Offer!</strong> ' + $(xml).find('offerdesc').attr('offer_desc') + '<br /> (Offer will be applied during checkout.)', 'offer-message', 'success');
				else
					HandleAlertMessage('Offer code applied', 'offer-message', 'success');
				if (a == 'multiselect-cartbegin')
					$('#checkout_form').submit();
				if (a == 'multiselect-payment')
					$('#offerCodeForm').submit();
			}
			else if ($(xml).find('sourcecode').length > 0) {
				HandleAlertMessage('<strong>Special Offer!</strong> Free gift with purchase - See details and product choices when you start checkout.', 'offer-message', 'success');
				var url = document.location.protocol + '//' + window.location.host + '/default.asp?path=/ecometry/selectoffer/selectoffer.aspx&processor=asp&asp_processor=store&action=multioffercode&t=' + window.mulitselect + '&nextaction=' + a;
				ShowOverLay({
					'id': 'offerselect',
					'url': url,
					'external': true
				});
			}
			else {
				$('#offer-message').hide();
				if (a == 'multiselect-cartbegin')
					$('#checkout_form').submit();
			}
		}
	};
	$.ajax({
		'url': url,
		'type': 'POST',
		'data': params,
		'dataType': 'xml',
		'success': callback,
		'error': FrameWorkErrorCallback
	});
	return false;
}
function FrameWorkErrorCallback(jqXHR, textStatus, errorThrown) {
	var xml = jqXHR.responseXML;
	var errorArray = [];
	$(xml).find('user_errors error').each(function(idx) {
		errorArray[errorArray.length] = $.trim($(this).text());
	});
	var continueMsg = 'Please click <a href="' + window.location.href + '">here</a> to continue.';
	if (errorArray.length > 0) {
		var errorHtml = '';
		for (var i = 0; i < errorArray.length; i++)
			errorHtml += errorArray[i] + '<br/>';
		window.errorHtml = errorHtml;
		errorHtml = errorHtml.replace('Please try your last action again.', continueMsg);
		HandleAlertMessage(errorHtml, 'user-message', 'alert');
	} else {
		HandleAlertMessage('We\'re Sorry - ' + continueMsg + '. You may have been idle too long, or run into an unexpected error.<br/>', 'user-message', 'alert');
	}
}
function OverLayTest() {
	var url = window.location.href;
	ShowOverLay({
		'id': 'siteoverlay',
		'url': url,
		'external': true
	});
}
function ShowOverLay(options) {
	var defaults = {
		'id': null,
		'width': 790,
		'height': 500,
		'speed': 200,
		'mask': '#000',
		'effect': 'apple',
		'load': true,
		'closeOnClick': false,
		'fixed': false,
		'oneInstance': false,
		'external': false
	};
	$.extend(defaults, options);
	//check that an id has been passed in and that the target exists
	if (defaults.id && $('#' + defaults.id).length > 0) {
		//check to see if overlay has already been initialized
		if ($('#' + defaults.id).data('loaded') == true)
			$('#' + defaults.id).overlay().load();
		//if overlay content is from another page, pull in html (currently must be internal page, no XSS)
		if (defaults.external)
			GetOverLaySrc(defaults);
		else
			InitOverLay(defaults);
	}
	return false;
}
function GetOverLaySrc(options) {
	var defaults = {
		'id': null,
		'url': null,
		'targets': ['div.col-766', 'div.col-751', 'div.col-768', 'div.col-650']
	};
	$.extend(defaults, options);
	if (defaults.id && defaults.url) {
		if ($('#' + defaults.id).length > 0) {
			$.ajax({
				'url': defaults.url,
				'dataType': 'html',
				'success': function(html) {
					//note, if protocol is not lining up, html may be empty, i.e. https = https
					var div = null;
					for (var i = 0; i < defaults.targets.length; i++) {
						div = $(html).find(defaults.targets[i]);
						if (div.length > 0) {
							if (/^[a-z\-\.]*(\d{3})$/i.test(defaults.targets[i]))
								defaults.width = parseInt(defaults.targets[i].substring(defaults.targets[i].indexOf('-') + 1)) + 24
							break;
						}
					}
					//if we could not find the content we were looking for, redirect to the page
					if (!div || div.length == 0)
						window.location = defaults.url;
					//otherwise, insert the content and init the overlay
					else {
						$('#' + defaults.id).find('div.overlay-content').html(div[0]);
						//$('#overlay-content :first-child').css('padding', '5px');
						InitOverLay(defaults);
					}
				}
			});
		}
	} else if (defaults.url)
		window.location = defaults.url;
}
function InitOverLay(defaults) {
	//set overlay height if specified
	if (defaults.height)
		$('#' + defaults.id).css({ 'height': defaults.height });
	//set overlay width if specified
	if (defaults.width)
		$('#' + defaults.id).css({ 'width': defaults.width });
	//initialize overlay
	$('#' + defaults.id).overlay({
		speed: defaults.speed,
		mask: defaults.mask,
		effect: defaults.effect,
		load: defaults.load,
		closeOnClick: defaults.closeOnClick,
		fixed: defaults.fixed,
		//oneInstance: defaults.oneInstance,
		onLoad: function() {
			$('#' + defaults.id).data('loaded', true);
		}
	});
}
//bind overlay links
$(function() {
	$('a[rel~="overlay"]').bind('click', function(e) {
		e.preventDefault();
		var href = this.href;
		ShowOverLay({
			'id': 'siteoverlay',
			'url': href,
			'external': true
		});
	});
});
