var app = (function (jQuery) {
	if (!jQuery) { alert(app.resources["MISSING_LIB"]); return null; }
	//Global dw private data goes here
	//dw scope public
	return {
		URLs: {},
		// holds dw specific urls, check htmlhead.isml for some example
		resources: {},
		// resource strings used in js
		constants: {},
		// platform constants, initialized in htmlhead.isml
		containerId: "content",
		ProductCache: null,
		// app.Product object ref to the current/main product
		clearDivHtml: "<div class=\"clear\"><!-- W3C Clearing --></div>",
		currencyCodes: {},
		// holds currency code/symbol for the site
		// default dialog box settings
		dialogSettings: {
			bgiframe: true,
			// this is required mainly for IE6 where drop downs bleed into dialogs!!!
			autoOpen: false,
			buttons: {},
			modal: true,
			overlay: { opacity: 0.5, background: "black" },
			height: 530,
			width: 800,
			title: '',
			// show: "slow". This is causing dialog to break in jquery 1.3.2
			hide: "normal",
			resizable: false
		},
		// app initializatoins called from jQuery(document).ready at the end of the file
		init: function () {
			// register initializations here
			// quick view dialog div
			jQuery("<div/>").attr("id", "QuickViewDialog").html(" ").appendTo(document.body);
		},
		// sub namespace app.ajax.* contains application specific ajax components
		ajax: {
			Success: "success",
			currentRequests: {},
			// request cache
			// ajax request to get json response
			// @param - reqName - String - name of the request
			// @param - async - boolean - asynchronous or not
			// @param - url - String - uri for the request
			// @param - data - name/value pair data request
			// @param - callback - function - callback function to be called
			getJson: function (options) {
				var thisAjax = this;
				// do not bother if the request is already in progress
				// and let go null reqName
				if (!options.reqName || !this.currentRequests[options.reqName]) {
					this.currentRequests[options.reqName] = true;
					if (options.async == "undefined") options.async = true;
					// make the server call
					jQuery.ajax({
						contentType: "application/json; charset=utf-8",
						dataType: "json",
						url: options.url,
						cache: true,
						async: options.async,
						data: options.data,
						success: function (response, textStatus) {
							thisAjax.currentRequests[options.reqName] = false;
							options.callback(response, textStatus);
						},
						error: function (request, textStatus, error) {
							if (textStatus === "parsererror") { alert(app.resources["BAD_RESPONSE"]); }
							options.callback({ Success: false, data: {} });
						}
					});
				}
			},
			// ajax request to load html response in a given container
			// @param - reqName - String - name of the request
			// @param - url - String - uri for the request
			// @param - data - name/value pair data request
			// @param - callback - function - callback function to be called
			// @param - selector - string - id of the container div/span (#mycontainer) - it must start with '#'
			load: function (options) {
				var thisAjax = this;
				// do not bother if the request is already in progress
				// and let go null reqname
				if (!options.reqName || !this.currentRequests[options.reqName]) {
					this.currentRequests[options.reqName] = true;
					// make the server call
					jQuery.ajax({
						dataType: "html",
						url: options.url,
						cache: true,
						data: options.data,
						success: function (response, textStatus) {
							thisAjax.currentRequests[options.reqName] = false;
							if (options.selector) { jQuery(options.selector).html(response); }
							(options.callback != undefined ? options.callback(response, textStatus) : null)
						},
						error: function (request, textStatus, error) {
							if (textStatus === "parsererror") { alert(app.resources["BAD_RESPONSE"]); }
							options.callback(null, textStatus);
						}
					});
				}
			}
		},
		// loads a product into a given container div
		// params
		// 		containerId - id of the container div, if empty then global app.containerId is used
		//		source - source string e.g. search, cart etc.
		//		label - label for the add to cart button, default is Add to Cart
		//		url - url to get the product
		//		id - id of the product to get, is optional only used when url is empty
		getProduct: function (options) { // id, source, start
			var cId = options.containerId || app.containerId;
			var source = options.source || "";
			var a2cBtnLabel = options.label || null;
			// show small loading image
			jQuery("#" + cId).html(app.showProgress("productloader"));
			var productUrl = options.url ? options.url : app.util.appendParamToURL(app.URLs.getProductUrl, "pid", options.id);
			productUrl = app.util.appendParamToURL(productUrl, "source", source);
			app.ajax.load({
				selector: "#" + cId,
				url: productUrl,
				callback: function (responseText, textStatus) {
					// update the Add to cart button label if one provided
					(a2cBtnLabel != null ? jQuery("#" + cId + " .addtocartbutton:last").html(a2cBtnLabel) : '');
				}
			});
		},
		// sub namespace app.util.* contains utility functions
		util: {
			// disables browser auto completion for the given element
			disableAutoComplete: function (elemId) { jQuery("#" + elemId).attr("autocomplete", "off"); },
			// trims a prefix from a given string, this can be used to trim
			// a certain prefix from DOM element IDs for further processing on the ID
			trimPrefix: function (str, prefix) { return str.substring(prefix.length); },
			// appends the parameter with the given name and
			// value to the given url and returns the changed url
			appendParamToURL: function (url, name, value) {
				var c = "?";
				if (url.indexOf(c) != -1) { c = "&"; }
				return url + c + name + "=" + encodeURIComponent(value);
			},
			// dynamically loads a CSS file
			loadCSSFile: function (url) {
				var elem = document.createElement("link");
				elem.setAttribute("rel", "stylesheet");
				elem.setAttribute("type", "text/css");
				elem.setAttribute("href", url);
				if (typeof elem != "undefined") {
					document.getElementsByTagName("head")[0].appendChild(elem);
					app.util.loadedCSSFiles.push(url);
				}
			},
			// array to keep track of the dynamically loaded CSS files
			loadedCSSFiles: [],
			// removes all dynamically loaded CSS files
			clearDynamicCSS: function () {
				for (var i = 0; i < app.util.loadedCSSFiles.length; i++) { app.util.unloadCSSFile(app.util.loadedCSSFiles[i]); }
			},
			// dynamically unloads a CSS file
			unloadCSSFile: function (url) {
				var candidates = document.getElementsByTagName("link");
				for (var i = candidates.length; i >= 0; i--) {
					if (candidates[i] && candidates[i].getAttribute("href") != null && candidates[i].getAttribute("href").indexOf(url) != -1) {
						candidates[i].parentNode.removeChild(candidates[i]);
					}
				}
			},
			// checks if cookies are enabled
			cookiesEnabled: function () {
				var currentCookie = document.cookie;
				document.cookie = "Enabled=true";
				var cookieValid = document.cookie;
				var result = false;
				if (cookieValid.indexOf("Enabled=true") != -1) { result = true; }
				document.cookie = currentCookie;
				return result;
			}
		},
		// Product quick view object
		quickView: {
			// bind browser events
			// options
			// buttonsSelector - css selector for the quickview button
			// imageSelector - css selector for the product image
			// buttonLinkSelector - css selector for quickview button link (a tag)
			// productNameLinkSelector - css selector for product name link (a tag)
			showIntDisclosure: function (options) {
				app.createDialog({
					id: 'QuickViewDialog',
					options: { height: 320, width: 470, dialogClass: 'quickview', title: '', resizable: false }
				});
				jQuery('#QuickViewDialog').dialog('open');
				app.getProduct({ containerId: "QuickViewDialog", source: options.source, url: options.url, label: options.label });
			},
			// close the quick view dialog
			close: function () { jQuery('#QuickViewDialog').dialog('close'); }
		},
		// helper method to create a dialog with the given options
		// options - dialog box options along with id of the container
		createDialog: function (options) { jQuery('#' + options.id).dialog(jQuery.extend({}, app.dialogSettings, options.options)); },
		// renders a progress indicator on the page; this function can be used
		// to indicate an ongoing progress to the user; the optional parameter "className"
		// can be used to attach an additional CSS class to the container
		showProgress: function (className) {
			var clazz = "loading";
			if (className) clazz += " " + className;
			return jQuery("<div class=\"" + clazz + "\"/>").append(jQuery("<img/>").attr("src", app.URLs.loadingSmallImg));
		}
	}
})(jQuery);

function openPopup(url, width, height, scroll) {
	if (url != null) {
		if (width != null && height != null) { window.open(url, "", "width=" + width + ", height=" + height + ", scrollbars=" + scroll + ", resizable=yes"); } 
		else { window.open(url, "", "scrollbars=no, resizable=yes"); }
	}
}
ProductCompare = {
	openPopup: function (url) {
		window.open( url, 'product_compare', 'width=800,height=600,scrollbars=yes,resizable=yes', true /* replace history in the popped up window */ ).focus();
	}
}
var miniCart = {
	ProductQty: null,
	ProductString: null,
	trigger: function (Quantity, ProductString, jqForm) {
		miniCart.ProductQty = Quantity;
		miniCart.ProductString = ProductString;
		var modal = $('#minicart01-modal');
		var modal_height = $(document).height();
		var box = $('#minicart01');
		var doc_w = $(window).width();
		var doc_h = $(window).height();
		//Show modal
		//modal.css({ 'width': doc_w, 'height': modal_height, 'display': 'block' })
		modal.css({ 'display': 'block' })
		.click(function () {
			//Create our 'click' event to hide the modal.
			$(this).fadeOut(300);
			box.css({ 'display': 'none' });
		});
		//Find the center of the screen for our minicart
		doc_w = parseInt((box.width() / 2));
		doc_h = parseInt(($(window).height() / 2) - (box.height() / 2));
		//Add the content into minicart before displaying
		jQuery('#minicart01 > #minicart-content > #minicart-product-qty').html(Quantity + ' ' + ProductString);
		//Display minicart
		box.css({ 'display': 'block', 'top': doc_h, 'left': '50%', 'margin-left': '-' + doc_w + 'px' });	
		//Add click event to 'x' to close minicart and fade out modal.
		jQuery('#minicart01 > #minicart-close > #minicart-close-action').unbind('click').click(function () {
			modal.fadeOut(300);
			box.css({ 'display': 'none' });
			window.location.reload();
		});
		//Add click event to 'Continue shopping' to close minicart and fade out modal.
		jQuery('#minicart01 > #minicart-content > #minicart-bottom-links > a#minicart-close').unbind('click').click(function () {
			modal.fadeOut(300);
			box.css({ 'display': 'none' });
			window.location.reload();
		});
		if (Quantity != null && ProductString != null && jqForm != null) { MiniCart.cartAdd(jQuery(jqForm)); }
	}
};
var miniCarthg = {
		ProductQty: null,
		ProductString: null,
		trigger: function (Quantity, ProductString, jqForm) {
			miniCart.ProductQty = Quantity;
			miniCart.ProductString = ProductString;
				
			if (Quantity != null && ProductString != null && jqForm != null) { MiniCart.cartAddhg(jQuery(jqForm)); }
		}
	};
jQuery(function () {
	jQuery('#btnAddCart').click(function () {
		AddtoCartValidation();
		if (!boolError) {
			var ProductQty = jQuery('input#Quantity[name="Quantity"]').val();
			var ProductName = $(this).attr('name');
			var FormSelector = '#' + jQuery(this).parents('form:first').attr('id');
			if (FormSelector.toString() == '#undefined') { FormSelector = '#' + jQuery('form[id*="dwfrm_product_addtocart"]').attr('id'); }
			if (jQuery('#isGC').length > 0 && isGiftCardAmountValid()) { miniCart.trigger(ProductQty, ProductName, FormSelector); }
			else { miniCart.trigger(ProductQty, ProductName, FormSelector); }
			
			var currentTotal = parseInt (jQuery ('#cartstatustext3rd').html());
			var toAdd = parseInt (jQuery ('#Quantity').val());
			var newTotal = currentTotal + toAdd;
			jQuery ('#cartstatustext3rd').html (newTotal.toString());
		}
		return false;
	});
});

//add to cart function for Holiday Gift quick view

jQuery(function () {
	jQuery('#btnAddCarthg').click(function () {
		AddtoCartValidation();
		if (!boolError) {
			jQuery("span.cartMessage").css('display','none');
			var ProductQty = jQuery('input#Quantity[name="Quantity"]').val();
			var ProductName = $(this).attr('name');
			var FormSelector = '#' + jQuery(this).parents('form:first').attr('id');
			if (FormSelector.toString() == '#undefined') { FormSelector = '#' + jQuery('form[id*="dwfrm_product_addtocart"]').attr('id'); }
			if (jQuery('#isGC').length > 0 && isGiftCardAmountValid()) { miniCarthg.trigger(ProductQty, ProductName, FormSelector); }
			else { miniCarthg.trigger(ProductQty, ProductName, FormSelector); }
		}
		return false;
	});
});
//end quick view function
//Functionality around the mini cart.
var MiniCart = {
	state: 0,
	//flag, whether cart is open or not
	url: '',
	//during page loading, the Demandware URL is stored here
	editurl: '',
	//during page loading, the Demandware URL is stored here
	totalURL: '',
	itemsURL: '',
	timer: null,
	//timer for automatic close of cart item view
	cartAdd: function (jqForm, progressImageSrc) {
		//get the data of the form as serialized string
		var postdata = jqForm.serialize();
		//disable form
		jqForm.attr('disabled', true);
		var handlerFunc = function (req) {
				//Form.enable(form);
				jqForm.attr('disabled', false);
				// replace the content
				jQuery('#minicart').html(req);
				miniCart.trigger(miniCart.ProductQty, miniCart.ProductString);
				cmDisplayShop5s();
				MiniCart.cartRefresh();
				}
		var errFunc = function (req) {
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
			// add the product	
			jQuery.ajax({ url: MiniCart.url, dataType: "html", type: "POST", data: postdata, success: handlerFunc, error: errFunc });
	},
	cartAddhg: function (jqForm, progressImageSrc) {
		//get the data of the form as serialized string
		var postdata = jqForm.serialize();
		//disable form
		jqForm.attr('disabled', true);
		var handlerFunc = function (req) {
				//Form.enable(form);
				jqForm.attr('disabled', false);
				// replace the content
				jQuery('#minicart').html(req);
				miniCart.trigger(miniCart.ProductQty, miniCart.ProductString);
				cmDisplayShop5s();
				MiniCart.cartRefresh();
				window.parent.location.reload();
			}
		var errFunc = function (req) {
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
			// add the product	
			jQuery.ajax({ url: MiniCart.url, dataType: "html", type: "POST", data: postdata, success: handlerFunc, error: errFunc });
	},
	cartAddfb: function (form, progressImageSrc) {
		// get the data of the form as serialized string
		var postdata = Form.serialize(form);
		// get button reference
		var addButtons = Form.getInputs(form, 'image', 'add');
		// the button to update
		var addButton = null;
		// disable form
		Form.disable(form);
		// it is an array of buttons, but we need only one all
		// other combinations are strange so far
		if (addButtons.length == 1) { addButton = addButtons[0]; }
		var previousImageSrc = null;
		// show progress indicator
		if (addButton != null) {
			previousImageSrc = addButton.src;
			addButton.src = progressImageSrc;
		}
		var handlerFunc = function (req) {
				// execute all scripts which are transmitted in the response
				// for example warning that the product is not in stock 
				req.responseText.evalScripts();
				req.responseText.stripScripts();
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
		var errFunc = function (req) {
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
			// show a loading message under the add to bag button
		var underbag = jQuery('#divunderaddtobag');
		var quickview = window.frames.quickview;
		if (quickview != undefined) {
			underbag = quickview.document.getElementById('divunderaddtobag');
			// fix for internet explorer because the elements
			// does not have yet the update function
			if (navigator.appVersion.match(/\bMSIE\b/)) { underbag = Element.extend(underbag); }
		}
		// this already disappeared during quick view
		if (underbag != undefined) { underbag.html("This item has been added to your bag"); }
		// add the product	
		new Ajax.Request(MiniCart.urlfb, { method: 'post', postBody: postdata, onSuccess: handlerFunc, onFailure: errFunc });
	},
	cartEdit: function (form, progressImageSrc) {
		// get the data of the form as serialized string
		var postdata = Form.serialize(form);
		// get button reference
		var addButtons = Form.getInputs(form, 'image', 'edit');
		// the button to update
		var addButton = null;
		// disable form
		Form.disable(form);
		// it is an array of buttons, but we need only one all
		// other combinations are strange so far
		if (addButtons.length == 1) { addButton = addButtons[0]; }
		var previousImageSrc = null;
		// show progress indicator
		if (addButton != null) {
			previousImageSrc = addButton.src;
			addButton.src = progressImageSrc;
		}
		var handlerFunc = function (req) {
				// execute all scripts which are transmitted in the response
				// for example warning that the product is not in stock 
				req.responseText.evalScripts();
				req.responseText.stripScripts();
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
		var errFunc = function (req) {
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
			// show a loading message under the add to bag button
		var underbag = jQuery('#divunderaddtobag');
		var quickview = window.frames.quickview;
		if (quickview != undefined) {
			underbag = quickview.document.getElementById('divunderaddtobag');
			// fix for internet explorer because the elements
			// does not have yet the update function
			if (navigator.appVersion.match(/\bMSIE\b/)) { underbag = Element.extend(underbag); }
		}
		// this already disappeared during quick view
		if (underbag != undefined) { underbag.html("<img src='" + progressImageSrc + "' alt='' />"); }
		// edit the product	
		jQuery.ajax({ url: MiniCart.editurl, dataType: "html", type: "POST", data: postdata, success: handlerFunc, error: errFunc });
	},
	cartRemove: function (form, progressImageSrc) {
		// get the data of the form as serialized string
		var postdata = form.serialize();
		var previousImageSrc = null;
		var handlerFunc = function (req) {
				// execute all scripts which are transmitted in the response
				// for example warning that the product is not in stock 
				req.responseText.evalScripts();
				req.responseText.stripScripts();
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
		var errFunc = function (req) {
				// hide progress indicator
				if (addButton != null) { addButton.src = previousImageSrc; }
				Form.enable(form);
			}
			// remove the product
			jQuery.ajax({ url: MiniCart.removeurl, type: "POST", data: postdata, async: false, success: function (data) {} });
	},
	cartClose: function () {
		if (MiniCart.timer != null) {
			clearTimeout(MiniCart.timer);
			MiniCart.timer = null;
			jQuery('#minicartcontent2').slideUp();
			jQuery.ajax({ url: MiniCart.totalURL, async: false, dataType: "html", type: "GET",
				success: function (data) { jQuery("#minicarttotal").html(data); }
			});
			jQuery.ajax({ url: MiniCart.itemsURL, async: false, dataType: "html", type: "GET",
				success: function (data) { jQuery("#qvFly").html(data); }
			});
			var quickview = window.frames.quickview;
		}
	},
	cartRefresh: function (checkoutstep) {
		$.ajax({ url: MiniCart.totalURL, async: false, dataType: 'html', type: 'GET',
			success: function (data) { jQuery('#minicarttotal').html(data); },
			error: function (xhr, stat, err) {}
		});
		jQuery.ajax({ url: MiniCart.itemsURL, async: false, dataType: 'html', type: 'GET',
			success: function (data) { jQuery('#qvFly').html(data); },
			error: function (xhr, stat, err) {}
		});
/*new Ajax.Updater('minicarttotal', MiniCart.totalURL,{asynchronous:false, evalScripts:true });
		new Ajax.Updater('qvFly', MiniCart.itemsURL,{asynchronous:false, evalScripts:true });*/
		// Address Page
		if (checkoutstep == "2") {
			new Ajax.Updater('ContainerAddress', MiniCart.showurlAddress, {
				asynchronous: false,
				evalScripts: true
			});
		}
		// Shipping Page
		if (checkoutstep == "3") {
			new Ajax.Updater('ContainerShipping', MiniCart.showurlShipping, {
				asynchronous: false,
				evalScripts: true
			});
			new Ajax.Updater('cShipping', MiniCart.showurlShippingInfo, {
				asynchronous: false,
				evalScripts: true
			});
			new Ajax.Updater('ajaxshippingaddressform', MiniCart.showurlShippingPromo, {
				asynchronous: false,
				evalScripts: true
			});
		}
		//Payment Page
		if (checkoutstep == "4") {
			new Ajax.Updater('ContainerPayments', MiniCart.showurlPayments, {
				asynchronous: false,
				evalScripts: true
			});
			new Ajax.Updater('cPayments', MiniCart.showurlPaymentsInfo, {
				asynchronous: false,
				evalScripts: true
			});
			new Ajax.Updater('editedorder', MiniCart.showurlOrderDetails, {
				asynchronous: false,
				evalScripts: true
			});
		}
	},
	// hook which can be replaced by individual pages/page types (e.g. cart)
	suppressSlideDown: function () { return false; }
}
var PopupDiv = {
	rti: null,
	show: function (arg) {
		var pSelector = $('popupbody');
		pSelector.css({
			'top': getTop() + 'px',
			'left': getLeft + 'px',
			'height': (getHeight() - 1) + 'px',
			'width': (getWidth() - scrollerWidth) + 'px',
			'display': 'block'
		});
		window.onresize = resizeHandler;
		window.onscroll = resizeHandler;
		PopupDiv.rti = arg;
		var popup = $(PopupDiv.rti);
		centerComponent(popup);
		popup.scrollTop = 0;
		$('#' + PopupDiv.rti).css({ 'display': 'block' });
	},
	close: function () {
		$('#' + PopupDiv.rti).attr('src', '').css({ 'display': 'none' });
		$('#popupbody').css({ 'display': 'none' });
	},
	showByUrl: function (url, arg, closeTimer, returnUrl) {
		var index = 0;
		PopupDiv.rti = arg;
		pSelector = $('#popupbody');
		pSelector.css({
			'top': getTop() + 'px',
			'left': getLeft + 'px',
			'height': (getHeight() - 1) + 'px',
			'width': (getWidth() - 100) + 'px'
		});
		window.onresize = resizeHandler;
		window.onscroll = resizeHandler;
		$('#' + PopupDiv.rti).css({ 'display': 'none' });
		$('#popupbody').css({ 'display': 'block' });
		var popup = $(PopupDiv.rti);
		popup.attr('src', url);
		//centerComponent(popup);
		popup.css({ 'display': 'block' });
	}
}

function resizeHandler() {
	centerVisibleComponent($(PopupDiv.rti));
	var pSelector = $('popupbody');
	pSelector.css({
		'top': getTop() + 'px',
		'left': getLeft() + 'px',
		'height': getHeight() + 'px',
		'width': getWidth() + 'px',
		'top': getTop() + 'px'
	});
}

function centerVisibleComponent(compo) {
	var ch = getTop() + getHeight() / 2 - compo.clientHeight / 2;
	var cw = getLeft() + getWidth() / 2 - compo.clientWidth / 2;
	compo.style.marginTop = ch + 'px';
	compo.style.marginLeft = cw + 'px';
}

function centerComponent(compo) {
	compo.style.visibility = 'hidden';
	compo.style.display = 'block';
	var ch = getTop() + getHeight() / 2 - compo.clientHeight / 2;
	var cw = getLeft() + getWidth() / 2 - compo.clientWidth / 2;
	compo.style.display = 'none';
	compo.style.visibility = '';
	compo.style.marginTop = ch + 'px';
	compo.style.marginLeft = cw + 'px';
} /* jQueried these 4 for now, replace/remove when possible*/

function getLeft() { var leftPos = jQuery(window).height(); return leftPos }
function getHeight() { var winHeight = jQuery(window).height(); return winHeight }
function getWidth() { var winWidth = jQuery(window).width(); return winWidth }
function getTop() { var scrollPos = jQuery(window).scrollTop(); return scrollPos }
//Get window info and return an object.

function getWindowInfo() {
	var wSel = $(window);
	var info = {
		top: wSel.scrollTop(),
		left: wSel.offset().left,
		width: wSel.width(),
		height: wSel.height()
	};
	return info;
}

function refreshTaxAddress_ex(form) {
	var shipToState = $('#ShipToState').val();
	var shipToCountry = $('#ShipToCountry').val();
	var ShipToCity = $('#ShipToCity').val();
	var ShipToZip = $('#ShipToZip').val();
}

function refreshTaxAddress(form) {
	var shipToState = document.getElementById('ShipToState').value;
	var ShipToCountry = document.getElementById('ShipToCountry').value;
	var ShipToCity = document.getElementById('ShipToCity').value;
	var ShipToZip = document.getElementById('ShipToZip').value;
	if (ShipToCountry == "US" || ShipToCountry == "CA") {
		if (shipToState != "" && ShipToCountry !== "" && ShipToCity !== "" && ShipToZip !== "") {
			// get the data of the form as serialized string
			var postdata = Form.serialize(form);
			// get the methods and update list
			new Ajax.Updater('ContainerAddress', taxUrl, { method: 'post', postBody: postdata, onSuccess: handlerFunc, onFailure: errFunc });
			var handlerFunc = function (req) { Form.enable(form); }
			var errFunc = function (req) { Form.enable(form); }
		}
	} else {
		// get the data of the form as serialized string
		var postdata = Form.serialize(form);
		document.getElementById('ShipToZip').value = "";
		// get the methods and update list
		new Ajax.Updater('ContainerAddress', taxUrl, { method: 'post', postBody: postdata, onSuccess: handlerFunc, onFailure: errFunc });
		var handlerFunc = function (req) { Form.enable(form); }
		var errFunc = function (req) { Form.enable(form); }
	}
}

function refreshCart(form) {
	var ShipToCountry = document.getElementById('ShipToCountry').value;
	var ShipToZip = document.getElementById('ShipToZip').value;
	if (ShipToCountry == "US") {
		// get the data of the form as serialized string
		var postdata = form.serialize();
		// get the methods and update list
		jQuery.ajax({ url: shipUrl, async: false, data: postdata, dataType: "html", type: "POST",
			success: function (content) { jQuery("#updatecartshipping").html(content); },
			error: function (content) { jQuery("#updatecartshipping").html("An error occurred. Please try again."); }
		});
	} else {
		// get the data of the form as serialized string
		document.getElementById('ShipToZip').value = "";
		var postdata = form.serialize();
		// get the methods and update list
		jQuery.ajax({ url: shipUrl, async: false, data: postdata, dataType: "html", type: "POST",
			success: function (content) { jQuery("#updatecartshipping").html(content); },
			error: function (content) { jQuery("#updatecartshipping").html("An error occurred. Please try again."); }
		});
	}
}

function CartTotalShippingTax() {
	$("shippingCalc").html('').hide();
}

function OrderHistoryAjax(Url) {
	var orderHistoryList = jQuery("#orderhistorylist");
	orderHistoryList.html("<div><img src='" + svrPath + "images/loadingAnimation.gif')}'> Loading...Please Wait</div>");
	jQuery.ajax({ url: Url, dataType: "html", type: "POST",
		success: function (data) { orderHistoryList.html(data); },
		error: function (data) { orderHistoryList.html("An error occurred. Please try again."); }
	});
}
//app_base
/* app.js version of the latest refapps */
var appbase = (function (jQuery) {
	if (!jQuery) { alert('Missing jQuery Library'); return null; }
	return {
		util: {
			// disables browser auto completion for the given element
			disableAutoComplete: function (elemId) { jQuery("#" + elemId).attr("autocomplete", "off"); },
			// trims a prefix from a given string, this can be used to trim
			// a certain prefix from DOM element IDs for further processing on the ID
			trimPrefix: function (str, prefix) { return str.substring(prefix.length); },
			// appends the parameter with the given name and
			// value to the given url and returns the changed url
			appendParamToURL: function (url, name, value) {
				var c = "?";
				if (url.indexOf(c) != -1) { c = "&"; }
				return url + c + name + "=" + encodeURIComponent(value);
			},
			// dynamically loads a CSS file
			loadCSSFile: function (url) {
				var elem = document.createElement("link");
				elem.setAttribute("rel", "stylesheet");
				elem.setAttribute("type", "text/css");
				elem.setAttribute("href", url);
				if (typeof elem != "undefined") {
					document.getElementsByTagName("head")[0].appendChild(elem);
					appbase.util.loadedCSSFiles.push(url);
				}
			},
			// array to keep track of the dynamically loaded CSS files
			loadedCSSFiles: [],
			// removes all dynamically loaded CSS files
			clearDynamicCSS: function () {
				for (var i = 0; i < appbase.util.loadedCSSFiles.length; i++) { appbase.util.unloadCSSFile(appbase.util.loadedCSSFiles[i]); }
			},
			// dynamically unloads a CSS file
			unloadCSSFile: function (url) {
				var candidates = document.getElementsByTagName("link");
				for (var i = candidates.length; i >= 0; i--) {
					if (candidates[i] && candidates[i].getAttribute("href") != null && candidates[i].getAttribute("href").indexOf(url) != -1) {
						candidates[i].parentNode.removeChild(candidates[i]);
					}
				}
			},
			// checks if cookies are enabled
			cookiesEnabled: function () {
				var currentCookie = document.cookie;
				document.cookie = "Enabled=true";
				var cookieValid = document.cookie;
				var result = false;
				if (cookieValid.indexOf("Enabled=true") != -1) { result = true; }
				document.cookie = currentCookie;
				return result;
			}
		}
	}
})(jQuery);
//global.js
var color = ""
var pageName = null;
var isVar = null;
var jsColor = "";

function preload_image(file) {
	var img = file.replace(/amp;/g, "");
	(new Image()).src = img;
}

function changeView(imgURL, imgID) { document.getElementById(imgID).src = imgURL }

function setUrl(link1, linkStyle, link2, imgId) {
	var query = document.getElementById(imgId).src;
	var colorLink = query.substring(query.lastIndexOf("_") + 1, query.length - 4);
	if (color == "") { document.location.href = link1 + link2; }
	else { document.location.href = link1 + linkStyle + '_' + colorLink + link2; }
}

function toggleVis(id) {
	var e = document.getElementById(id);
	if (e.style.display == 'block') e.style.display = 'none';
	else e.style.display = 'block';
}

function toggleVisOn(id) {
	var e = document.getElementById(id);
	if (e != null) { e.style.display = 'block'; }
}

function toggleVisOff(id) {
	var e = document.getElementById(id);
	if (e != null) { e.style.display = 'none'; }
}

function toggleAddress() {
	if (document.getElementById('UseShippingAsBillingFlag').value == 'true') {
		document.getElementById('divCass').style.display = 'none';
		document.getElementById('divDass').style.display = 'block';
		//document.getElementById('buttons').style.marginTop = '-30px';       		
		document.getElementById('UseShippingAsBillingFlag').value = 'false'
	} else {
		document.getElementById('divCass').style.display = 'block';
		document.getElementById('divDass').style.display = 'none';
		document.getElementById('UseShippingAsBillingFlag').value = 'true'
	}
}

function setElementValue(id, value) {
	var e = document.getElementById(id);
	e.value = value;
}

function getNextElement(iElement) {
	var parentForm = iElement.form;
	for (i = 0; i < parentForm.length; i++) {
		if (parentForm.elements[i] == iElement) if (parentForm.elements[i + 1]) return parentForm.elements[i + 1];
	}
	return null;
}

function autotab(iCtl, iMax) {
	var nextElement, textValue = iCtl.value;
	if (textValue.length == iMax) {
		nextElement = getNextElement(iCtl);
		if (nextElement) {
			nextElement.select();
			nextElement.focus();
		}
	}
}

function empty(object) {
	if (object == null) { return true; }
	if (object.toString().length == 0) { return true; }
	return false;
}
//class hashtable

function Hashtable() {
	this.hash = new Array();
	this.keys = new Array();
	this.location = 0;
}
Hashtable.prototype.get = function (key) {
	return this.hash[key];
}
Hashtable.prototype.contains = function (key) {
	if (this.hash[key] != null) { return true; } 
	else { return false; }
}
Hashtable.prototype.put = function (key, value) {
	if (value == null) { return null; }
	if (this.hash[key] == null) { this.keys[this.keys.length] = key; }
	this.hash[key] = value;
}

function addToCartFromQuickView(FormID, continueImage) {
	MiniCart.cartAdd(FormID, continueImage);
	return false;
}

function preLoadImagesMain() {
	preload_image(svrPath + 'images/backgrounds/bg_quickview.gif');
	preload_image(svrPath + 'images/backgrounds/bg_quickview.png');
	preload_image(svrPath + 'images/backgrounds/bg_drop_sm.png');
	preload_image(svrPath + 'images/backgrounds/bg_drop_lg.png');
	preload_image(svrPath + 'images/backgrounds/bg_minicart.jpg');
	preload_image(svrPath + 'images/backgrounds/bg_searchform.png');
}

function preLoadImagesPD() {
	preload_image(svrPath + 'images/backgrounds/bg_quickview.gif');
	preload_image(svrPath + 'images/backgrounds/bg_quickview.png');
	preload_image(svrPath + 'images/backgrounds/bg_flyout_shad.png');
	preload_image(svrPath + 'images/backgrounds/bg_prodImageTh.gif');
}

function widgetShow(id) { jQuery('#' + id).slideDown() }

function mcDivShow(id) {
	var d1 = 'mcImg' + id;
	var d2 = 'mcDesc' + id;
	var d3 = 'arrDiv' + id;
	//alert(document.getElementById(d1).style.display);
	if (document.getElementById(d1).style.display == 'none') {
		document.getElementById(d1).style.display = 'block';
		document.getElementById(d2).style.display = 'block';
		document.getElementById(d3).src = svrPath + 'images/buttons/arrw_mc_dwn.gif';
	} else {
		document.getElementById(d1).style.display = 'none';
		document.getElementById(d2).style.display = 'none';
		document.getElementById(d3).src = svrPath + 'images/buttons/arrw_mc.gif';
	}
}
document.onclick = function (e) {
	e = e || event
	var target = e.target || e.srcElement
	var box = document.getElementById("divSearchWidget")
	var sbox = document.getElementById("srchBoxMain")
	do {
		if (box == target || sbox == target) { return true }
		target = target.parentNode
	} while (target)
	// Click was outside the box, hide it.
	if (box != null && box.style.display != 'none') { Effect.SlideUp('divSearchWidget'); }
}

function queryString(key) {
	var re = new RegExp("[?&]" + key + "=([^&$]*)", "i");
	var offset = location.search.search(re);
	if (offset == -1) return null;
	return RegExp.$1;
}

function searchWidg() {
	if (document.getElementById("divSearchWidget").style.display == 'none') { Effect.SlideDown('divSearchWidget'); }
	else { return false; }
}

function ismaxlength(obj) {
	var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length > mlength) obj.value = obj.value.substring(0, mlength)
}
//jQuery extSlide plugin, facilitates some functions that were using scriptaculous
(function ($) {
	$.extend($.fn, {
		slideLeftShow: function (speed, callback) {
			return this.animate({ width: "show" }, speed, callback); },
		slideLeftHide: function (speed, callback) {
			return this.animate({ width: "hide" }, speed, callback);
		},
		slideLeftToggle: function (speed, callback) {
			return this.animate({ width: "toggle" }, speed, callback);
		},
		slideRightShow: function (speed, callback) {
			return this.animate({
				width: "show"
			}, {
				step: function (now, data) {
					var w = Math.ceil(now);
					if (typeof (data.origLeft) == 'undefined') {
						var position = $(this).css('position');
						if (position == 'static') { $(this).css('position', 'relative'); }
						data.origPos = position;
						data.origLeft = data.end + parseInt($(this).css('left')) || 0;
					}
					$(this).css({ left: data.origLeft - (data.start + w) });
					if (w == data.end) $(this).css('position', data.origPos);
				},
				duration: speed,
				complete: callback
			});
		},
		slideRightHide: function (speed, callback) {
			return this.animate({
				width: "hide"
			}, {
				step: function (now, data) {
					var w = Math.ceil(now);
					if (typeof (data.origLeft) == 'undefined') {
						var position = $(this).css('position');
						if (position == 'static') { $(this).css('position', 'relative'); }
						data.origPos = position;
						data.origLeft = parseInt($(this).css('left')) || 0;
					}
					$(this).css({ left: data.origLeft + (data.start - w) });
					if (w == 0) $(this).css({
						left: data.origLeft,
						position: data.origPos
					});
				},
				duration: speed,
				complete: callback
			});
		},
		slideRightToggle: function (speed, callback) {
			return this.animate({
				width: "toggle"
			}, {
				step: function (now, data) {
					var w = Math.ceil(now);
					if (typeof (data.origLeft) == 'undefined') {
						var position = $(this).css('position');
						if (position == 'static') { $(this).css('position', 'relative'); }
						data.origPos = position;
						data.origLeft = data.end + parseInt($(this).css('left')) || 0;
					}
					if (data.start == 0) {
						if (w == data.end) $(this).css('position', data.origPos);
						$(this).css({ left: data.origLeft - (data.start + w) });
					} else {
						$(this).css({ left: data.origLeft + (data.start - w) });
						if (w == 0) $(this).css({
							left: data.origLeft,
							position: data.origPos
						});
					}
				},
				duration: speed,
				complete: callback
			});
		}
	});
})(jQuery); /*common footer functions*/

function validateEmail() {
	var reg = /^[\w_\-.]+\@[^.]+(\.[^\.]+){1,}$/; // regular expression for email
	var footerRecipientEmailValid = jQuery("#signupEmail").val().match(reg) ? true : false;
	if (footerRecipientEmailValid) {
		jQuery("#footerRecipientEmailErrorId").css(display, 'none');
		return true;
	} else {
		jQuery("#footerRecipientEmailErrorId").css("display", ((footerRecipientEmailValid) ? "none" : "block"));
		return false;
	}
}

function onFocusEmail(emailField) {
	var defaultFieldValue = emailFieldDefaultValue; //uses js value defined in-page, server side;
	if (emailField.value == defaultFieldValue) { emailField.value = ''; }
}

function onBlurEmail(emailField) {
	var defaultFieldValue = emailFieldDefaultValue; //uses js value defined in-page, server side;
	if (emailField.value == '') { emailField.value = defaultFieldValue; }
}
//Function used to set session cookie, used in Channel Advisor support

function setCookie(c_name, value) {
	var sitedomain = jsSiteDomain; //uses js value defined in-page, server side;
	document.cookie = c_name + "=" + escape(value) + ";path=/" + ";domain=" + sitedomain;
}

function qvShow(pid, cgid, navid) {
	var url = jsQuickViewUrl; //set in page
	if (cgid != null) { var vcgid = '&cgid=' + cgid; }
	else { var vcgid = ''; }
	
	if (navid != null) { var vnavid = '&navid=' + navid; }
	else { var vnavid = ''; }
	
	url = url + '?pid=' + pid + vcgid + vnavid;
	qvPopUp(url);
}

function qvPopUp(url) {
	//$('<div id=\'popup_container\'></div>').appendTo(document.body);
	$('<div id="popup_container"><iframe frameborder="0" scrolling="no" style="display: block;" class="quickviewHop" allowtransparency="true" name="quickview" id="quickview" src="' + url + '"></iframe></div>').appendTo(document.body);
	var popupDiv = $('#popup_container')
	var height = jQuery(window).height() * .90;
	var popupHandle = {
		modal: true,
		position: 'center',
		width: 585,
		height: 425,
		autoOpen: false,
		overlay: { opacity: 0.5, background: "black" },
		dialogClass: 'acctHop',
		close: function () { popupDiv.remove(); }
	}
	popupDiv.dialog(popupHandle);
	$(".ui-dialog-titlebar").remove();
	popupDiv.dialog('open');
}

function pdShow(pid, cgid, navid) {
	var url = jsPdpUrl; //set in page	
	
	if (cgid != null) { var vcgid = '&cgid=' + cgid; }
	else { var vcgid = ''; }
	
	if (navid != null) { var vnavid = '&navid=' + navid; }
	else { var vnavid = ''; }
	
	url = url + '?pid=' + pid + vcgid + vnavid;
	parent.location = url;
}

function catShow(cgid, navid) {
	var url = jsPlpUrl; //set in page
	
	if (navid != null) { var vnavid = '&navid=' + navid; }
	else { var vnavid = ''; }
	
	url = url + '?cgid=' + cgid + vnavid;
	parent.location = url;
}

function linkShow(cid) {
	var url = jsContentLinkUrl; //set in page		
	
	if (cid == null) { return false; }
	
	url = url + '?cid=' + cid;
	parent.location = url;
}

function qvShowfb(pid, cgid, navid) {
	var url = jsFBQuickViewUrl; //set in page
	
	if (cgid != null) { var vcgid = '&cgid=' + cgid; }
	else { var vcgid = ''; }
	
	if (navid != null) { var vnavid = '&navid=' + navid; }
	else { var vnavid = ''; }
	
	url = url + '?pid=' + pid + vcgid + vnavid;
	PopupDiv.showByUrl(url, 'quickview');
}

function cartPopUp(url, jobj) { // REMOVE FROM CART POP UP
	var form = jobj.parents('form').attr('id');
	var row = jobj.parents('tr');
	var product_name = row.find('div.name a').text();
	var dialog_title = 'Important';
	$('<div id="popup_container"><p>Are you sure you want to remove ' + product_name + ' from Shopping Cart?</p></div>').appendTo(document.body);
	var popupDiv = $('#popup_container');
	var popupHandle = {
		modal: true,
		position: 'center',
		title: dialog_title,
		width: 375,
		height: 400,
		autoOpen: false,
		dialogClass: 'qvPopUp_container',
		close: function () { popupDiv.remove(); },
		buttons: {
			'No': function () { popupDiv.dialog('close'); },
			'Yes': function () { window.location = url; return false; }
		}
	}
	popupDiv.dialog(popupHandle).dialog('open');
	return;
}
//initialize document functions/set bindings
jQuery(document).ready(function () {
	// init app
	app.init();
	//minicart show/hide bindings
	jQuery('#minicarttotal a').click(function () {
		if (jQuery.browser.msie == true && jQuery.browser.version == '8.0') { jQuery('#miniCartDiv').show(); }
		else { jQuery('#miniCartDiv').slideDown(); }
	});
	jQuery('#minicartClose').click(function () {
		jQuery('#miniCartDiv').slideUp();
	});
	//cookie test code
	if (navigator.cookieEnabled == 0 && jQuery('#cookietest').length > 0) {
		jQuery('#cookietest').css('display', 'block');
	}
});
//searchsuggest.js
(function (appbase) {
	if (appbase) {
		appbase.searchsuggest = {
			// configuration parameters and required object instances
			acListTotal: 0,
			acListCurrent: -1,
			acDelay: 100,
			acURL: null,
			acFormId: null,
			acSearchId: null,
			acResultsId: null,
			acSearchField: null,
			acResultsDiv: null,
			fieldDefault: null,
			init: function (formId, fieldId, fieldDefault, resultsId, url) {
				// initialize vars
				appbase.searchsuggest.acFormId = "#" + formId;
				appbase.searchsuggest.acSearchId = "#" + fieldId;
				appbase.searchsuggest.acResultsId = "#" + resultsId;
				appbase.searchsuggest.acURL = url;
				appbase.searchsuggest.fieldDefault = fieldDefault;
				// disable browser auto comlete
				appbase.util.disableAutoComplete(fieldId);
				// create the results div
				jQuery("body").append("<div id=\"" + resultsId + "\"></div>");
				// register mostly used vars (jQuery object)
				appbase.searchsuggest.acSearchField = jQuery(appbase.searchsuggest.acSearchId);
				appbase.searchsuggest.acResultsDiv = jQuery(appbase.searchsuggest.acResultsId);
				// reposition div
				appbase.searchsuggest.repositionResultsDiv();
				// on blur listener
				appbase.searchsuggest.acSearchField.blur(function () {
					setTimeout("appbase.searchsuggest.clear()", 200)
				});
				// on key up listener
				appbase.searchsuggest.acSearchField.keyup(function (e) {
					// get keyCode (window.event is for IE)
					var keyCode = e.keyCode || window.event.keyCode;
					var lastVal = appbase.searchsuggest.acSearchField.val();
					// check an treat up and down arrows
					if (appbase.searchsuggest.updownArrow(keyCode)) { return; }
					// check for an ENTER or ESC
					if (keyCode == 13 || keyCode == 27) {
						appbase.searchsuggest.clear();
						return;
					}
					// if is text, call with delay
					setTimeout(function () {
						appbase.searchsuggest.suggest(lastVal)
					}, appbase.searchsuggest.acDelay);
				});
				// on focus listener (clear default value)
				appbase.searchsuggest.acSearchField.focus(function () {
					var val = appbase.searchsuggest.acSearchField.val();
					if (val == appbase.searchsuggest.fieldDefault) { appbase.searchsuggest.acSearchField.val(""); }
				});
				// on submit we do not submit the form, but change the window location
				// in order to avoid https to http warnings in the browser
				jQuery(appbase.searchsuggest.acFormId).submit(function () {
					var searchUrl = jQuery(appbase.searchsuggest.acFormId).attr("action");
					var searchTerm = appbase.searchsuggest.acSearchField.val();
					window.location = appbase.util.appendParamToURL(searchUrl, "q", searchTerm);
					return false;
				});
			},
			// trigger suggest action
			suggest: function (lastValue) {
				// get the field value
				var part = appbase.searchsuggest.acSearchField.val();
				// if it's empty clear the resuts box and return
				if (part == "") {
					appbase.searchsuggest.clear();
					return;
				}
				// if it's equal the value from the time of the call, allow
				if (lastValue != part) { return; }
				// build the request url
				var reqUrl = appbase.util.appendParamToURL(appbase.searchsuggest.acURL, "q", part);
				// get remote data as JSON
				jQuery.getJSON(reqUrl, function (json) {
					// get the total of results
					var ansLength = appbase.searchsuggest.acListTotal = json.suggestions.length;
					// if there are results populate the results div
					if (ansLength > 0) {
						var newData = "";
						// create a div for each result
						for (i = 0; i < ansLength; i++) {
							newData += "<div class=\"unselected\"><div class=\"suggestionterm\">" + json.suggestions[i].suggestion + "</div>";
							newData += "<span class=\"hits\">" + json.suggestions[i].hits + "</span></div>";
						}
						// update the results div
						appbase.searchsuggest.acResultsDiv.html(newData);
						appbase.searchsuggest.acResultsDiv.css("display", "block");
						// for all divs in results
						var divs = jQuery(appbase.searchsuggest.acResultsId + " > div");
						// on mouse over clean previous selected and set a new one
						divs.mouseover(function () {
							divs.each(function () { this.className = "unselected"; });
							this.className = "selected";
						});
						// on click copy suggestion to search field, hide the list and submit the search
						divs.click(function () {
							var str = this.childNodes[0].innerHTML;
							appbase.searchsuggest.acSearchField.val(str.replace(/\&amp;/g, '&'));
							appbase.searchsuggest.clear();
							jQuery(appbase.searchsuggest.acFormId).submit();
						});
					} else { appbase.searchsuggest.clear(); }
				});
			},
			// clear suggestions
			clear: function () {
				appbase.searchsuggest.acResultsDiv.html("");
				appbase.searchsuggest.acResultsDiv.css("display", "none");
			},
			// reposition the results div accordingly to the search field
			repositionResultsDiv: function () {
				// get the input position
				var inPos = appbase.searchsuggest.acSearchField.offset();
				var inTop = inPos.top;
				var inLeft = inPos.left;
				// get the field size
				var inHeight = appbase.searchsuggest.acSearchField.height();
				var inWidth = appbase.searchsuggest.acSearchField.width();
				// apply the css styles
				appbase.searchsuggest.acResultsDiv.addClass("suggestions");
			},
			// treat up and down key strokes defining the next selected element
			updownArrow: function (keyCode) {
				if (keyCode == 40 || keyCode == 38) {
					if (keyCode == 38) { // keyUp
						if (appbase.searchsuggest.acListCurrent == 0 || appbase.searchsuggest.acListCurrent == -1) {
							appbase.searchsuggest.acListCurrent = appbase.searchsuggest.acListTotal - 1;
						} else { appbase.searchsuggest.acListCurrent--; }
					} else { // keyDown
						if (appbase.searchsuggest.acListCurrent == appbase.searchsuggest.acListTotal - 1) {
							appbase.searchsuggest.acListCurrent = 0;
						} else { appbase.searchsuggest.acListCurrent++; }
					}
					// loop through each result div applying the correct style
					appbase.searchsuggest.acResultsDiv.children().each(function (i) {
						if (i == appbase.searchsuggest.acListCurrent) {
							var str = this.childNodes[0].innerHTML;
							appbase.searchsuggest.acSearchField.val(str.replace(/\&amp;/g, '&'));
							this.className = "selected";
						} else { this.className = "unselected"; }
					});
					return true;
				} else {
					// reset
					appbase.searchsuggest.acListCurrent = -1;
					return false;
				}
			}
		} // end searchsuggest
	} else {
		// namespace has not been defined yet
		alert("appbase namespace is not loaded yet!");
	}
})(appbase);
jQuery(document).ready(function () {
	swapValues = [];
	jQuery(".swap_value").each(function (i) {
		swapValues[i] = jQuery(this).val();
		jQuery(this).focus(function () {
			if (jQuery(this).val() == swapValues[i]) { jQuery(this).val("") }
		}).blur(function () {
			if (jQuery.trim(jQuery(this).val()) == "") { jQuery(this).val(swapValues[i]) }
		})
	});
	appbase.searchsuggest.init("SimpleSearchForm", "srchBoxMain", "${Resource.msg('simplesearch.searchtext','search',null)}", "suggestions", searchSuggestURL);
});
// function to display pop up during checkout

function cartEditPopUp(url, jobj) {
	var form = jobj.parents('form').attr('id');
	var row = jobj.parents('tr');
	var product_name = row.find('div.name a').text();
	var dialog_title = 'Edit Product';
	$('<div id="popup_container"><iframe frameborder="0" scrolling="no" style="display: block; height: 647px;" class="quickviewHop" allowtransparency="true" name="quickview" id="quickview" src="' + url + '"></iframe></div>').appendTo(document.body);
	var popupDiv = $('#popup_container');
	var popupHandle = {
		modal: true,
		position: 'center',
		title: dialog_title,
		width: 750,
		height: 647,
		autoOpen: false,
		dialogClass: 'qvPopUp_container',
		close: function () { popupDiv.remove(); }
	}
	popupDiv.dialog(popupHandle);
	$(".ui-dialog-titlebar").remove();
	popupDiv.dialog('open');
	return;
}

function cartRemovePopUp(url, jobj) {
	var form = jobj.parents('form').attr('id');
	var row = jobj.parents('tr');
	var product_name = row.find('div.name a').text();
	var dialog_title = 'Edit Product';
	$('<div id="popup_container"><iframe frameborder="0" scrolling="no" style="display: block;" class="quickviewHop" allowtransparency="true" name="quickview" id="quickview" src="' + url + '"></iframe></div>').appendTo(document.body);
	var popupDiv = $('#popup_container');
	var popupHandle = {
		modal: true,
		position: 'center',
		title: dialog_title,
		width: 414,
		height: 200,
		autoOpen: false,
		dialogClass: 'qvPopUp_container',
		close: function () { popupDiv.remove(); }
	}
	popupDiv.dialog(popupHandle);
	$(".ui-dialog-titlebar").remove();
	popupDiv.dialog('open');
	return;
}

function TellFrieandPopUp(url, jobj, newWindow) {
	if (newWindow == undefined || newWindow == "") { var newWindow = false; }
	
	var form = jobj.parents('form').attr('id');
	var row = jobj.parents('tr');
	var product_name = row.find('div.name a').text();
	var dialog_title = 'Edit Product';
	if (newWindow == 'true') { window.open(url + '&lt1=_new'); }
	else {
		$('<div id="popup_container"><iframe frameborder="0" scrolling="no" style="display: block; height: 730px;" class="quickviewHop" allowtransparency="true" name="quickview" id="quickview" src="' + url + '"></iframe></div>').appendTo(document.body);
		var popupDiv = $('#popup_container');
		var popupHandle = {
			modal: true,
			position: 'center',
			title: dialog_title,
			width: 760,
			height: 730,
			autoOpen: false,
			dialogClass: 'qvPopUp_container',
			close: function () { popupDiv.remove(); }
		}
		popupDiv.dialog(popupHandle);
		$(".ui-dialog-titlebar").remove();
		popupDiv.dialog('open');
	}
	return;
}

function getGridProductImg(Url, pid) {
	var productImageDiv = jQuery("#thumbnail_" + pid);
	var productImageDivParent = productImageDiv.parent();
	jQuery.ajax({ url: Url, dataType: "html", type: "POST",
		success: function (data) {
			productImageDiv.remove();
			productImageDivParent.prepend(data);
		},
		error: function (data) {
			productImageDiv.css({
				display: 'block',
				width: '378px'
			}).html("An error occurred. Please try again.");
		}
	});
}
String.prototype.trimEnd = function (c) {
	if (c) { return this.replace(new RegExp(c.escapeRegExp() + "*$"), ''); }
	return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function (c) {
	if (c) { return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), ''); }
	return this.replace(/^\s+/, '');
}
String.prototype.escapeRegExp = function () {
	return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};

function GetParamFromURL(key, query) {
	if (!query) { query = window.location.search; }
	var re = new RegExp("[?|&]" + key + "=(.*?)&");
	var matches = re.exec(query + "&");
	if (!matches || matches.length < 2) { return ""; }
	return decodeURIComponent(matches[1].replace("+", " "));
}

function SetParamFromURL(key, value, query) {
	query = query || window.location.search;
	var q = query + "&";
	var re = new RegExp("[?|&]" + key + "=.*?&");
	
	if (!re.test(q)) { q += key + "=" + encodeURI(value); }
	else { q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&"); }
	
	q = q.trimStart("&").trimEnd("&");
	return q[0] == "?" ? q : q = "?" + q;
}
/* - Derek Carr
 * - After a swatch is clicked, this function
 *   swaps out the product image.
 * - To implement, add this attribute to the swatch:
 *  	onClick="javascript: Grid_SwapProductImageFromSwatch (this);"
 */
function Grid_SwapProductImageFromSwatch(from) {
	//Cycle through the selectors to find out which page we're on
	var ProductThumbSelector = $(from).parent().parent().find('.gridthumb');
	if (ProductThumbSelector.html() == null) {
		ProductThumbSelector = $(from).parent().parent().parent().find('.gridthumb');
	}
	//Get the product image anchor
	var ProductThumbAnchor = ProductThumbSelector.parent().parent().find('.product-image');
	//Get the URL for the product image anchor
	var ProductThumbLink = ProductThumbAnchor.attr('href');
	var ToColorURL = $(from).attr('src').split('_');
	var ToColorURL = ToColorURL[2];
	var NewURL = SetParamFromURL('selectedColor', ToColorURL, ProductThumbLink);
	
	if (NewURL[0] == '?') { NewURL = NewURL.substring(1, NewURL.length); }
	
	ProductThumbAnchor.attr('href', NewURL);
	//Remove the _SWATCH suffix and append the primary image suffix
	var ProductThumb_SWAP = $(from).attr('src').replace('_1_SWATCH.jpg', '_1.jpg');
	//Find the old preset
	var OldPreset = ProductThumb_SWAP.split('/');
	//Search for LuckyBrandJeans in our URL to get the offset
	for (var i = 0; i < OldPreset.length; i++) {
		//Find our string, increment, replace the old preset
		if (OldPreset[i] == 'LuckyBrandJeans') {
			OldPreset[i + 1] = 'prod_grid';
			//Finish URL reconstruction
			ProductThumb_SWAP = OldPreset.join('/');
			break;
		}
	}
	//Make the swap
	ProductThumbSelector.attr('src', ProductThumb_SWAP);
}
