<!--
/* file version: $LastChangedDate: 2008-09-18 09:44:52 -0400 (Thu, 18 Sep 2008) $ */

  function openURL(form){

  	var URL = form.goURL.options[form.goURL.selectedIndex].value;
          top.location.href = URL;

  }

  function submitForm(myform)
  {
     myform.submit();
  }

  /*
     this function is used on the cart page to autoselect the giftnote when
     a user selects the gift wrap option
   */
  function autoSelectGiftNote() {

    if (document.cartform.wrap.checked &&
        !document.cartform.giftnote.checked) {

      document.cartform.giftnote.click();
    }
  }

 /**
  * <p>This function is used to limit the number of characters entered into a form
  * field.  Created for the gift note textarea
  **/
  function textLimit(field, maxlen) {
     if (field.value.length > maxlen) {
       field.value = field.value.substring(0, maxlen);
     }
  }

  /**
  * The email campaign popup.  First check the form fields to
  * make sure we can submit.
  */
  function emailSignup(URL, theForm) {
    // need to make sure the required fields are not null
    openWindow = true;

    // check to see if we have an email address at all
    addressEntered = theForm.emailAddress.value;
    if (trim(addressEntered) == "") {
      openWindow = false;
    }

    // check to see if we have an email address with an @ symbol
    if (addressEntered.indexOf("@") == -1 ) {
      openWindow = false;
    }

    // don't open window if we had a form error
    if (openWindow) {
      newwindow=open(URL,"","scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=480,height=500");
    }
  }

  /* The product details popup */
  function detailsPopup(URL) {
    newwindow=open(URL,"","scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=450,height=525");
  }

  /* The notify me when in-stock popup */
  function notifyMePopup(URL) {
    newwindow=open(URL,"","scrollbars=yes,toolbar=no,directories=no,menubar=no,resizable=yes,status=yes,width=480,height=500");
  }

  function trim(inputString) {
     // Removes leading and trailing spaces from the passed string. Also removes
     // consecutive spaces and replaces it with one space. If something besides
     // a string is passed in (null, custom object, etc.) then return the input.
     if (typeof inputString != "string") { return inputString; }
     var retValue = inputString;
     var ch = retValue.substring(0, 1);
     while (ch == " ") { // Check for spaces at the beginning of the string
        retValue = retValue.substring(1, retValue.length);
        ch = retValue.substring(0, 1);
     }
     ch = retValue.substring(retValue.length-1, retValue.length);
     while (ch == " ") { // Check for spaces at the end of the string
        retValue = retValue.substring(0, retValue.length-1);
        ch = retValue.substring(retValue.length-1, retValue.length);
     }
     while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
        retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
     }
     return retValue; // Return the trimmed string back to the user
  } // Ends the "trim" function

  	var Tools = {};

  	Tools.getViewportDimensions = function() {
  		return {
  			width: self.innerWidth || (document.documentElement.clientWidth || document.body.clientWidth),
			height: self.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight) };
  	}

  	Tools.ImagePreloader = { images: new Array() };

  	Tools.ImagePreloader.preload = function(imageUrls) {
  		$A(imageUrls).each(function(url) { Tools.ImagePreloader._preload(url); });
  	}

  	Tools.ImagePreloader._preload = function(imageUrl) {
  		var image = new Image();
  		this.images.push(image);

  		image.src = imageUrl;
  	}

  	var PopupWindow = { registeredPopup: null };

  	PopupWindow.cleanupState = function() {
  		try {
  			if (!this.registeredPopup
	  			|| !this.registeredPopup.closed) {
	  			return;
	  		}
	  	} catch (e) {
	  	}

	  	this.registeredPopup = null;
  	}

  	PopupWindow.notifyOpener = function() {
  		try {
  			if (window.opener
  				&& window.opener.PopupWindow
  				&& window.opener.PopupWindow.registerPopup) {
  				if (!window.opener.PopupWindow.registerPopup(window)) {
  					window.close();
  				}
  			}
		} catch (e) {}
  	}

  	PopupWindow.registerPopup = function(popupWindow) {
  		this.cleanupState();

  		if (this.registeredPopup) {
  			return this.registeredPopup == popupWindow;
  		}

  		this.registeredPopup = popupWindow;

  		return true;
  	}

  	PopupWindow.open = function(url, parameters) {
  		this.cleanupState();

  		try {
  			if (this.registeredPopup)
  				this.registeredPopup.close();
  		} catch (e) {}

  		this.registeredPopup = window.open(url, "tbs_popup_window", parameters);
  	}

	var PopupBoot = Class.create();
	PopupBoot.prototype = {
		initialize: function() {
			var _this = this;

			Event.observe(window, 'load', function () { _this._window_onLoad(); });
			Tools.ImagePreloader.preload(['/images/bgCenter_quickShop.gif', '/images/bgTop_quickShop.gif', '/images/bClose.gif', '/images/greenRule.gif', '/images/bProductDetail.gif', '/images/bAddToCart.gif', '/images/bgBottom_quickShop.gif']);
		},

		_window_onLoad: function() {
			var _this = this;

			this.popupContentDiv = $('popupContent');
			if (!this.popupContentDiv) {
				new Insertion.Bottom(document.body, '<div id="popupContent" style="display:none;left:0px;top:0px"></div>');
				this.popupContentDiv = $('popupContent');
			}

			Event.observe(this.popupContentDiv, 'resize', function () { _this.adjustPopupPosition(); } );
			Event.observe(window, 'resize', function () { _this.adjustPopupPosition(); });

			// JS: disabled per TBSE-100: Remove "Follow Me" functionality on Product Pop Up
			// Event.observe(window, 'scroll', function () { _this.adjustPopupPosition(); });

	  		Element.getElementsByClassName(document.body, 'bs_crosssell_div')
	  			.each( function(element) {
					Event.observe(element, 'mouseover', function(event) {_this.showBuyButton(element)});
					Event.observe(element, 'mouseout', function(event) {_this.hideBuyButton(element)});
				} );

	  		Element.getElementsByClassName(document.body, 'bs_category_div')
	  			.each( function(element) {
					Event.observe(element, 'mouseover', function(event) {_this.showBuyButton(element)});
					Event.observe(element, 'mouseout', function(event) {_this.hideBuyButton(element)});
				} );

	  		Element.getElementsByClassName(document.body, 'pd_cat_feature_div')
	  			.each( function(element) {
					Event.observe(element, 'mouseover', function(event) {_this.showBuyButton(element)});
					Event.observe(element, 'mouseout', function(event) {_this.hideBuyButton(element)});
				} );
		},

		toggleBuyButton: function(element, state) {
			var buttonElement = Element.getElementsByClassName(element, 'buy_now_button');
  			if (!buttonElement || buttonElement.length == 0) return;
  			if (state)
	  			buttonElement[0].style.visibility='visible';
	  		else
	  			buttonElement[0].style.visibility='hidden';
	  	},

	  	showBuyButton: function(element) {
	  		this.toggleBuyButton(element, true);
	  	},

	  	hideBuyButton: function(element) {
	  		this.toggleBuyButton(element, false);
	  	},

	  	positionPopup: function(left, top) {
  			this.popupContentDiv.style.width = 'auto';
  			this.popupContentDiv.style.height = 'auto';
  			this.popupContentDiv.style.left = left + "px";
  			this.popupContentDiv.style.top = top + "px";
   		},

  		detachPopupFormHandlers: function() {
	  		if (!this.popupFormHandlersCache) return;

	  		this.popupFormHandlersCache.each( function(cacheEntry) {
	  			Event.stopObserving(cacheEntry.element, 'submit', cacheEntry.handler);
	  		});
  		},

  		attachPopupFormHandlers: function() {
	  		this.popupFormHandlersCache = [];

	  		var _this = this;

	  		Element.getElementsBySelector(this.popupContentDiv, 'form')
	  			.each( function(formElement) {
	  				var cacheEntry = {
	  					element: formElement,
	  					handler: function (event) { _this.submitBuyPopup(event, formElement); }
	  				};

	  				Event.observe(cacheEntry.element, 'submit', cacheEntry.handler );

	  				_this.popupFormHandlersCache.push(cacheEntry);
	  			});
  		},

  		fillPopup: function(html) {
  			this.detachPopupFormHandlers();

  			this.popupContentDiv.innerHTML = html;
  			this.attachPopupFormHandlers();

  			html.evalScripts();
  		},

  		adjustPopupPosition: function() {
  			if (!this.popupVisible) return;

  			var _this = this;

  			var pos = { x:parseFloat(this.popupContentDiv.style.left || 0), y:parseFloat(this.popupContentDiv.style.top || 0) };
  			pos = this.adjustPositionToVisibleSpace(pos);

  			this._runEffect(function() {
  				return new Effect.Move(_this.popupContentDiv, { x:pos.x, y:pos.y, mode:'absolute', duration:0.2 });
  			});
  		},

  		adjustPositionToVisibleSpace: function(pos) {
  			var maxY = Position.realOffset($('container'))[1] + Tools.getViewportDimensions().height - 20 - this.popupContentDiv.getHeight();
  			if (pos.y > maxY) pos.y = maxY;
  			var minY = Position.realOffset($('container'))[1] + 20;
  			if (pos.y < minY) pos.y = minY;

  			return pos;
  		},

  		_preShow: function() {
  			if (this.popupVisible) {
  				this.hideBuyPopup();
  			}
  		},

  		_doShow: function(responseText, element, suggestPopupPositionFunction) {
  			var _this = this;

			this._cancelEffect();

  			Element.hide(this.popupContentDiv);
			this.fillPopup(responseText);
	  		var pos = suggestPopupPositionFunction(element, this.popupContentDiv);
			pos = this.adjustPositionToVisibleSpace(pos);
	  		this.positionPopup(pos.x, pos.y);

  			this._runEffect(function() {
  				return new Effect.Grow(_this.popupContentDiv, { afterFinish: function() { _this.popupVisible=true; _this.adjustPopupPosition(); }, duration:1 } );
  			});
  		},

  		_cancelEffect: function() {
  			while (Effect.Queue.size() > 0) {
  				var effect = Effect.Queue.toArray()[0];
  				effect.cancel();
  				if (effect.options && effect.options.afterFinishInternal) {
  					effect.options.afterFinishInternal(effect);
  				}
  			}
  		},

  		_runEffect: function(effectCreator) {
  			this._cancelEffect();
	  		effectCreator();
  		},

  		_showUrlPopup: function(element, suggestPopupPositionFunction, url) {
  			var _this = this;

  			this._preShow();

	  		new Ajax.Request(url, {
	  			onException: function(requestor, exception) {
	  				// alert('exception: ' + exception);
	  			},

	  			onComplete: function(transport) {

	  				if (200 != transport.status) {
	  					// alert('status: ' + transport.status);
	  					return;
	  				}

	  				_this._doShow(transport.responseText, element, suggestPopupPositionFunction);
	  			}
	  		});
  		},

  		showAddMultipleItemsToCartPopup: function(element, suggestPopupPositionFunction, productIds, skuIds, quantities) {
  			this._showUrlPopup(element, suggestPopupPositionFunction, '/bodyshop/browse/buy_multiple_popup.jsp?productIds='+productIds+'&skuIds='+skuIds+'&quantities='+quantities);
  		},

  		showBuyPopup: function(element, suggestPopupPositionFunction, productId, categoryId) {
  			this._showUrlPopup(element, suggestPopupPositionFunction, '/bodyshop/browse/product_detail_popup.jsp?productId='+productId+'&categoryId='+categoryId);
  		},

  		hideBuyPopup: function() {
  			this.popupVisible = false;

  			this._cancelEffect();
  			Element.hide(this.popupContentDiv);
  		},

  		formSerialize: function(form) {
	  		var params = form.serialize(true);
			form.getInputs('image').each( function(element) {
				if (!element.disabled && element.name) {
		        	var key = element.name;
	    	    	params[key + '.x'] = '0';
	        		params[key + '.y'] = '0';
	        	}
	        });

	        return params;
  		},

  		submitBuyPopup: function(event, form) {
  			var _this = this;
  			var form = $(form);
  			Event.stop(event);

	  		new Ajax.Request(form.readAttribute('action'), {
	  			parameters: _this.formSerialize(form),

	  			onException: function(requestor, exception) {
	  				// alert('exception: ' + exception);
	  			},

	  			onComplete: function(transport) {

	  				if (200 != transport.status) {
	  					// alert('status: ' + transport.status);
	  					return;
	  				}

	  				_this.fillPopup(transport.responseText);
	  				_this.adjustPopupPosition();
	  			}
	  		});

  		}
   	}

	var ProductDetailPicker = Class.create();
	ProductDetailPicker.prototype = {
	initialize: function(data, selectedSku) {
			this.data = data;
			this.popupForm = $('pdp_form');
			this.colorOutOfStockAlert = $('pdp_colorOutOfStock');
			this.colorSelector = $('pdp_colorSelector');
			this.sizeSelector = $('pdp_sizeSelect');
			this.sizePriceSelector = $('pdp_sizePriceSelect');
			this.skuIdHiddenField = $('pdp_skuId');
			//this.colorName = $('pdp_colorName');
			this.colorSelectEnvelope = $('pdp_colorSelectEnvelope');
			this.shoppingBottom = $('pdp_shoppingBottom');

			var colorAndSize = this.getSkuColorAndSize(selectedSku);
			if (!colorAndSize) {
				this.selectColor('0');
			} else {
				this.selectColor(colorAndSize.color.id);
				this.selectSize(colorAndSize.colorSizeSku.size.id);
			}

			if (this.getColorCount() == 1 && this.data['0'].name == '') {
				Element.hide(this.colorSelectEnvelope);
			}
		},

		getColorCount: function() {
			var cnt = 0;
			for (var colorId in this.data) {
				cnt ++;
			}
			return cnt;
		},
		
		getSizeCount: function() {
			var cnt = 0;
			for (var colorId in this.data) {
				var color = this.data[colorId];
				if(color.colorSizeSkus.length > cnt ){		
				   cnt = color.colorSizeSkus.length;
				}
			}
			return cnt;
		},

		getSkuColorAndSize: function(skuId) {
			for (var colorId in this.data) {
				var color = this.data[colorId];
				for (var i=0; i<color.colorSizeSkus.length; i++) {
					var colorSizeSku = color.colorSizeSkus[i];

					if (colorSizeSku.sku.id == skuId) {
						return {color: color, colorSizeSku: colorSizeSku};
					}
				}
			}

			return null;
		},

		getSelectedSizeId: function() {
			var selectedSizeId = -1;
			Form.getInputs(this.popupForm, 'radio', 'sizeSelector')
				.each( function(element) {
					if (element.checked) {
						selectedSizeId = $F(element);
					}
				});
			return selectedSizeId;
		},

		getSizeDivForSize: function(size) {
			return Element.getElementsBySelector(this.sizePriceSelector, '.' + size.cssClassName).first();
		},

		getSizeRadioForSize: function(size) {
			return Element.getElementsBySelector(this.getSizeDivForSize(size), "input").first();
		},

		getPriceDivForSize: function(size) {
			return Element.getElementsByClassName(this.getSizeDivForSize(size), 'price').first();
		},

		getSizeAlertDivForSize: function(size) {
			return Element.getElementsByClassName(this.getSizeDivForSize(size), 'sizeAlert').first();
		},

		getMusterPriceDivForSku: function(sku) {
			return $('__price_' + sku.id);
		},

		selectColor: function(id) {
			var color = this.data[id];
			this.selectedColor = color;

			// find the appropriate swatch and use selectedSwatch class
			if (this.colorSelector) {
				Element.immediateDescendants(this.colorSelector)
					.each( function(element) {
						if (Element.hasClassName(element, color.cssClassName)) {
							Element.addClassName(element, 'selectedSwatch');
						} else {
							Element.removeClassName(element, 'selectedSwatch');
						}
					});
			}

			//this.colorName.innerHTML = color.name;

			var _this = this;

			// save the currently selected size id (so that we can later restore it, if it
			// is still usable with the new color
			var originalSelectedSizeId = this.getSelectedSizeId();

			// disable and hide all sizes first
			if (this.sizeSelector) {
				Element.immediateDescendants(this.sizeSelector)
					.each( function(element) {
						var input = Element.getElementsBySelector(element, "input").first();
						Element.hide(element);
						input.checked = false;
						Form.Element.disable(input);
					});
			}
			
			
			// Hide all product images
			for (var im=0; im<_this.getColorCount(); im++) {
				Element.hide("_img_"+im);
			}
			// Show current product image
			Element.show("_img_"+id);
			
			// Hide all detail divs then show current detail div
			for (var de=0; de<_this.getColorCount(); de++) {
				Element.hide("__detail_"+de);
			}
			Element.show("__detail_"+id);
				
				// Hide all prices
				for (var colorId in this.data) {
					var cColor = this.data[colorId];
					for (var j=0; j<cColor.colorSizeSkus.length; j++){
						var csSku = cColor.colorSizeSkus[j];
						var pId = "__price_"+csSku.sku.id;
						Element.hide(pId);
					}
				}
				var colorSizeSku = color.colorSizeSkus[0];
				var priceId = "__price_"+colorSizeSku.sku.id;
				
				//Show current price
				Element.show(priceId);
				
			var colorIsOutOfStock = true; // will change to false if at least one combination with size is in stock
			Element.hide(this.colorOutOfStockAlert);
			// show valid combinations and enable those in stock
	

			// if all sizes are out of stock, display color out of stock message
			// and clear the hidden input field with currently selected SKU
			
			_this.skuIdHiddenField.value = colorSizeSku.sku.id;
			_this.enableSubmit(true)
		
		},

		selectSize: function(id) {
			var _this = this;

			this.selectedColor.colorSizeSkus
				.each( function(colorSizeSku) {
					if (colorSizeSku.size.id == id) {
						_this.skuIdHiddenField.value = colorSizeSku.sku.id;
						_this.enableSubmit(true);

						var sizeRadio = _this.getSizeRadioForSize(colorSizeSku.size);
						if (sizeRadio != null) {
							sizeRadio.checked = true;
						}
					}
				});
		},

		enableSubmit: function(enable) {
			if (enable) {
				Element.show(this.shoppingBottom);
			} else {
				Element.hide(this.shoppingBottom);
			}
		}
	};
	
	var ProductDetailSizePicker = Class.create();
	ProductDetailSizePicker.prototype = {
	initialize: function(data, selectedSku) {
			
			this.data = data;
			this.popupForm = $('pdp_form');
			this.colorOutOfStockAlert = $('pdp_colorOutOfStock');
			this.colorSelector = $('pdp_colorSelector');
			this.sizeSelector = $('pdp_sizeSelect');
			this.sizePriceSelector = $('pdp_sizePriceSelect');
			this.skuIdHiddenField = $('pdp_skuId');
			this.shoppingBottom = $('pdp_shoppingBottom');


			var colorAndSize = this.getSkuColorAndSize(selectedSku);
			if (!colorAndSize) {
				this.selectSize('0');
			} else {
				this.selectSize(colorAndSize.colorSizeSku.size.id);
			}
		},

		getColorCount: function() {
			var cnt = 0;
			for (var colorId in this.data) {
				cnt ++;
			}
			return cnt;
		},
		
		getSizeCount: function() {
			var cnt = 0;
			for (var colorId in this.data) {
				var color = this.data[colorId];
				if(color.colorSizeSkus.length > cnt ){		
				   cnt = color.colorSizeSkus.length;
				}
			}
			return cnt;
		},

		getSkuColorAndSize: function(skuId) {
			for (var colorId in this.data) {
				var color = this.data[colorId];
				for (var i=0; i<color.colorSizeSkus.length; i++) {
					var colorSizeSku = color.colorSizeSkus[i];

					if (colorSizeSku.sku.id == skuId) {
						return {color: color, colorSizeSku: colorSizeSku};
					}
				}
			}

			return null;
		},

		getSelectedSizeId: function() {
			var selectedSizeId = -1;
			Form.getInputs(this.popupForm, 'radio', 'sizeSelector')
				.each( function(element) {
					if (element.checked) {
						selectedSizeId = $F(element);
					}
				});
			return selectedSizeId;
		},

		getSizeDivForSize: function(size) {
			return Element.getElementsBySelector(this.sizePriceSelector, '.' + size.cssClassName).first();
		},

		getSizeRadioForSize: function(size) {
			return Element.getElementsBySelector(this.getSizeDivForSize(size), "input").first();
		},

		getPriceDivForSize: function(size) {
			return Element.getElementsByClassName(this.getSizeDivForSize(size), 'price').first();
		},

		getSizeAlertDivForSize: function(size) {
			return Element.getElementsByClassName(this.getSizeDivForSize(size), 'sizeAlert').first();
		},

		getMusterPriceDivForSku: function(sku) {
			return $('__price_' + sku.id);
		},

		selectSize: function(id) {
		
			var _this = this;
			var _skuId = '';
			
			// Hide all detail divs then show current detail div
			for (var de=0; de<_this.getSizeCount(); de++) {
				Element.hide("__detail_"+de);
			}
			Element.show("__detail_"+id);
			
			//select correct item in drop down
			var size_select = document.getElementById("size_select");
			size_select.selectedIndex = id;
			
			// Hide all price divs then show current price div
			for (var pr=0; pr<_this.getSizeCount(); pr++) {
				Element.hide("__price_"+pr);
			}
			Element.show("__price_"+id);
			
			//TODO: check if item is in stock and enable/disable qty
			var colorIsOutOfStock = true; // will change to false if at least one combination with size is in stock
			
			Element.hide(this.colorOutOfStockAlert);
			
			// show valid combinations and enable those in stock

			// if all sizes are out of stock, display color out of stock message
			// and clear the hidden input field with currently selected SKU
			
			//set this for commerce
			if(id != null && id < this.data.size) {
				_skuId = this.data[id].colorSizeSkus[0].sku.id;
			}
			else{
				_skuId = this.data[0].colorSizeSkus[0].sku.id;
			}
			_this.skuIdHiddenField.value = _skuId;
			_this.enableSubmit(true)
		},

		enableSubmit: function(enable) {
			if (enable) {
				Element.show(this.shoppingBottom);
			} else {
				Element.hide(this.shoppingBottom);
			}
		}
	};
	
	
	var ProductDetailPopup = Class.create();
	ProductDetailPopup.prototype = {
		initialize: function(data, selectedSku) {
			this.data = data;
			this.popupForm = $('pdp_form');
			this.colorOutOfStockAlert = $('pdpd_colorOutOfStock');
			this.colorSelector = $('pdp_colorSelector');
			this.sizeSelector = $('pdp_sizeSelect');
			this.sizePriceSelector = $('pdp_sizePriceSelect');
			this.skuIdHiddenField = $('pdp_skuId');
			this.colorName = $('pdp_colorName');
			this.colorSelectEnvelope = $('pdp_colorSelectEnvelope');
			this.shoppingBottom = $('pdp_shoppingBottom');

			var colorAndSize = this.getSkuColorAndSize(selectedSku);
			if (!colorAndSize) {
				this.selectColor('0');
			} else {
				this.selectColor(colorAndSize.color.id);
				this.selectSize(colorAndSize.colorSizeSku.size.id);
			}

			if (this.getColorCount() == 1 && this.data['0'].name == '') {
				Element.hide(this.colorSelectEnvelope);
			}
		},

		getColorCount: function() {
			var cnt = 0;
			for (var colorId in this.data) {
				cnt ++;
			}
			return cnt;
		},

		getSkuColorAndSize: function(skuId) {
			for (var colorId in this.data) {
				var color = this.data[colorId];
				for (var i=0; i<color.colorSizeSkus.length; i++) {
					var colorSizeSku = color.colorSizeSkus[i];

					if (colorSizeSku.sku.id == skuId) {
						return {color: color, colorSizeSku: colorSizeSku};
					}
				}
			}

			return null;
		},

		getSelectedSizeId: function() {
			var selectedSizeId = -1;
			Form.getInputs(this.popupForm, 'radio', 'sizeSelector')
				.each( function(element) {
					if (element.checked) {
						selectedSizeId = $F(element);
					}
				});
			return selectedSizeId;
		},

		getSizeDivForSize: function(size) {
			return Element.getElementsBySelector(this.sizePriceSelector, '.' + size.cssClassName).first();
		},

		getSizeRadioForSize: function(size) {
			return Element.getElementsBySelector(this.getSizeDivForSize(size), "input").first();
		},

		getPriceDivForSize: function(size) {
			return Element.getElementsByClassName(this.getSizeDivForSize(size), 'price').first();
		},

		getSizeAlertDivForSize: function(size) {
			return Element.getElementsByClassName(this.getSizeDivForSize(size), 'sizeAlert').first();
		},

		getMusterPriceDivForSku: function(sku) {
			return $('__price_' + sku.id);
		},

		selectColor: function(id) {
			var color = this.data[id];
			this.selectedColor = color;

			// find the appropriate swatch and use selectedSwatch class
			if (this.colorSelector) {
				Element.immediateDescendants(this.colorSelector)
					.each( function(element) {
						if (Element.hasClassName(element, color.cssClassName)) {
							Element.addClassName(element, 'selectedSwatch');
						} else {
							Element.removeClassName(element, 'selectedSwatch');
						}
					});
			}

			this.colorName.innerHTML = color.name;

			var _this = this;

			// save the currently selected size id (so that we can later restore it, if it
			// is still usable with the new color
			var originalSelectedSizeId = this.getSelectedSizeId();

			// disable and hide all sizes first
			if (this.sizeSelector) {
				Element.immediateDescendants(this.sizeSelector)
					.each( function(element) {
						var input = Element.getElementsBySelector(element, "input").first();
						Element.hide(element);
						input.checked = false;
						Form.Element.disable(input);
					});
			}

			var colorIsOutOfStock = true; // will change to false if at least one combination with size is in stock

			// show valid combinations and enable those in stock
			color.colorSizeSkus
				.each( function(colorSizeSku) {
					var sizeDiv = _this.getSizeDivForSize(colorSizeSku.size);
					var sizeRadio = _this.getSizeRadioForSize(colorSizeSku.size);
					var priceDiv = _this.getPriceDivForSize(colorSizeSku.size);
					var sizeAlertDiv = _this.getSizeAlertDivForSize(colorSizeSku.size);
					var musterPriceDiv = _this.getMusterPriceDivForSku(colorSizeSku.sku);

					// show valid combination and set it's sku id
					Element.show(sizeDiv);

					// if the sku is in stock, show price and enable radio button
					if (colorSizeSku.sku.inStock) {
						// note, that we have at least one in-stock size combination
						colorIsOutOfStock = false;

						// fill in price and show it
						priceDiv.innerHTML = musterPriceDiv.innerHTML;
						Element.show(priceDiv);
						Element.hide(sizeAlertDiv);

						// enable radio
						if (sizeRadio) {
							Form.Element.enable(sizeRadio);
						}
					} else {
						// sku is out of stock, hide price, show alert
						Element.hide(priceDiv);
						Element.show(sizeAlertDiv);

						// disable radio
						if (sizeRadio) {
							Form.Element.disable(sizeRadio);
						}
					}
				});

			// if all sizes are out of stock, display color out of stock message
			// and clear the hidden input field with currently selected SKU
			if (colorIsOutOfStock) {
			    //alert("color ouf of stock");
				Element.show(this.colorOutOfStockAlert);
				this.skuIdHiddenField.value = '';
				this.enableSubmit(false);
			} else {
				//alert("color in stock");
				// sizes are not all out of stock, select either the original selected one (if available)
				// or the first in-stock available combination
				Element.hide(this.colorOutOfStockAlert);

				var inStockSelected = false;

				for (var i=0; i<color.colorSizeSkus.length; i++) {
					var colorSizeSku = color.colorSizeSkus[i];
					var sizeRadio = this.getSizeRadioForSize(colorSizeSku.size);

					if (!inStockSelected && colorSizeSku.sku.inStock) {
						this.selectSize(colorSizeSku.size.id, sizeRadio);
						inStockSelected = true;
					}

					if (colorSizeSku.size.id == originalSelectedSizeId) {
						this.selectSize(colorSizeSku.size.id, sizeRadio);
						break;
					}
				}
			}
		},

		selectSize: function(id) {
			var _this = this;

			this.selectedColor.colorSizeSkus
				.each( function(colorSizeSku) {
					if (colorSizeSku.size.id == id) {
						_this.skuIdHiddenField.value = colorSizeSku.sku.id;
						_this.enableSubmit(true);

						var sizeRadio = _this.getSizeRadioForSize(colorSizeSku.size);
						if (sizeRadio != null) {
							sizeRadio.checked = true;
						}
					}
				});
		},

		enableSubmit: function(enable) {
			if (enable) {
				Element.show(this.shoppingBottom);
			} else {
				Element.hide(this.shoppingBottom);
			}
		}
	};

  	function suggestPopupPosition_ProductPage(element, popupDiv) {
  		return { x:597-popupDiv.getWidth()+Position.cumulativeOffset($('container'))[0], y:161 };
  	}

  	function suggestPopupPosition_CategoryPage(element, popupDiv) {
  		return { x:459-popupDiv.getWidth()/2+Position.cumulativeOffset($('container'))[0], y:Position.cumulativeOffset(element.up())[1] };
  	}

	var bs_PopupBoot = null;
	function bs_initPopupBoot(isEnabled) {
		if (arguments.length == 0) {
			isEnabled = false;
		}
		if (isEnabled && !bs_PopupBoot) {
			bs_PopupBoot = new PopupBoot();
		}
	}

	function bs_showBuyPopup(element, suggestPopupPositionFunction, productId, categoryId) {
		bs_PopupBoot.showBuyPopup(element, suggestPopupPositionFunction, productId, categoryId);
	}

	function bs_showAddMultipleItemsToCartPopup(element, suggestPopupPositionFunction, productIds, skuIds, quantities) {
		bs_PopupBoot.showAddMultipleItemsToCartPopup(element, suggestPopupPositionFunction, productIds, skuIds, quantities);
	}

	function bs_hideBuyPopup() {
		bs_PopupBoot.hideBuyPopup();
	}

	function bs_showPopup(popupId) {
  		new Ajax.Request('/bodyshop/global/invoke_popup.jsp', {
  			asynchronous: false, // has to be false not to annoy popup blockers
  			method: 'GET',
  			parameters: { popupId: popupId },

  			onException: function(requestor, exception) {
  				// alert('exception: ' + exception);
  			},

  			onComplete: function(transport) {

  				if (200 != transport.status) {
  					// alert('status: ' + transport.status);
  					return;
  				}

  				transport.responseText.evalScripts();
  			}
  		});
	}

	new PeriodicalExecuter(function() {PopupWindow.notifyOpener();}, 1);

	/* toggleTab Added for Rebranding project - controls tabs on product page. */
	function toggleTab(number){
	    
           for(var i=1; i<=4; i++) {
            if (number==i) {
	            document.getElementById("tablink_"+i).className="on";
	            document.getElementById("content_"+i).className="show top";
			} else if (number+1==i) {
	            document.getElementById("tablink_"+i).className="part";
	            document.getElementById("content_"+i).className="top";
            } else {
	            document.getElementById("tablink_"+i).className="";
	            document.getElementById("content_"+i).className="top";
            }
           }
       }
-->
