(function(app){
	if (app) {
		// add Product object to dw namespace
		app.Product = function(response) {
			// product private data
			
			var colorAttrib    = "variationColor";

			var model 			= response.data;

			var mainAttrGroup	= null;

			var myContainerId	= "";

			var isLoadingVar	= false;

			var loadVariants	= function(thisProduct) {
				isLoadingVar = true;
				// build the url and load variants data
				var url = app.util.appendParamToURL(app.URLs.getVariants, {"pid": thisProduct.pid, "format": "json"} );
				var result = app.ajax.getJson({
					url: url,
					data: {},
					callback: function(data){

						if (!data.Success) {
							return;
						}
						model.variations.variants = data.variations.variants;
						isLoadingVar = false; // we have loaded the variants
						jQuery(thisProduct).trigger("VariationsLoaded", ["loadVariants"]);
						// we should use the class 'selected on the LI element.  it is more
						// reliable since then the canchor class.  done in product.isml
						// search for: one("VariationsLoaded"
						// jQuery('.emptyswatch a#default').click();
						/*
						// issue 1:  the original implementation didn't put the class
						//   emptyswatch on the initially selected color swatch
						// issue 2:  due to the late execution of this script, the 
						//   swatches show for a second and get hidden then.  Ugly
						// All swatches will aleways have the class emptyswatch 
						// assigned.  Now swatches always stay.
						if ( jQuery('.emptyswatch').length < 2) 
							jQuery('#pdpvariationColorvar').hide();
						*/ 
					}
				});
			}

			var loadRecommendations = function(containerId) {
				if (jQuery(containerId+" #pdpCarouselDiv ul li").length > 0) {
					jQuery(containerId+" #pdpCarouselDiv ul").jcarousel({scroll: 1});
					// create tooltips event handler
					app.tooltip({id: containerId+" #pdpCarouselDiv ul li", options: {
							bodyHandler: function() {
								return jQuery(this).children(".pdpTooltip").html();
							}
					}});
				}				
			}

			var getOptionsDiv	= function(thisProduct) {

				if (model.isOption && !model.master) {

					var pdpOpt = jQuery(thisProduct.containerId+" .product_options:last select");

					pdpOpt.change(function(e){
						var vals = this.options[this.selectedIndex].value.split("%?%"); // 0 = value, 1 = price
						e.data = {id: this.id, val: vals[0], price: vals[1]};
						thisProduct.optionSelected(e);
					});
					
					// let us get the currently selected value and intilize the ui
					pdpOpt.each(function(i) {
						var vals = this.options[this.selectedIndex].value.split("%?%"); // 0 = value, 1 = price					
						thisProduct.optionSelected({data : {id: this.id, val: vals[0], price: vals[1]}});
					});
				}
			}

			var getAddToCartBtn = function(thisProduct,isQuickViewFlag) {
				var addToCartBtn = jQuery(thisProduct.containerId+" .addtocart_button:last").click(function(e) {
					if (model.master || model.variant) {
						if (thisProduct.selectedVar == null) {
							return false;
						}
						
						// inserted by JN
						/*
						 * We have a small problem here:  The ref app only  
						 * changes the selected variation is color and size
						 * are selected.  Therefore the previous test of the
						 * thisProduct.selectedVar will always be good.
						 * the code further down responsible for this is this line:
						 * if (this.selectedIndex == 0) { return; }
						 * But if you remove that line, the ref app assumes that 
						 * there is no variant available!  All color swatches will
						 * be masked :-(  I assume the behavior for ref app works
						 * opposite to Burton:  Burton: 1st color then size; Ref app
						 * 1st size and then color.
						 * Hence I put in here a small test.  we should always have
						 * a size dropdown with that ID
						 * 
						 *  OK, we need to narrow it down further more:
						 *  If we have a drop down field, the selected value has to match the
						 *  the value of the currently selected attribute 
						 */
						if ( !allVariationsSelected() )
						{
							return false;
						}
						
						// and now we need to make sure that the selected color is actually selectable
						// jQuery( that.containerId+" #pdp"+ "variationColor" +"var li a[innerHTML=True Black]" ).parent().hasClass( "unselectable" )
						
						thisProduct.selectedOptions.pid = thisProduct.selectedVar.id;
						thisProduct.selectedOptions.masterPid = thisProduct.pid;
						
					}
					else {
						// check if we are adding a bundle/productset to the cart
						if (model.bundle || model.productSet) {							
							var subProducts = thisProduct.subProducts;
							var comma 		= ",";
							var tempQty 	= "";
							var subproduct 	= null;
							
							thisProduct.selectedOptions.childPids = "";
														
							if (model.productSet) {
								thisProduct.selectedOptions.Quantity = "";
							}
							
							for (var i = 0; i < subProducts.length; i++) {
								subproduct = subProducts[i];
								
								if (i == subProducts.length - 1) {
									comma = ""; // at the end of the list
								}
								
								// see if any of the sub products are variations, if so then get the selected variation id
								// from selectedVar property
								if (subproduct.variant || subproduct.master) {									
									thisProduct.selectedOptions.childPids += subproduct.selectedVar.id+comma;
								}
								else {
									thisProduct.selectedOptions.childPids += subproduct.selectedOptions.pid+comma;
								}
								
								var tempPid = subproduct.selectedOptions.pid;
								subproduct.selectedOptions.pid = null;
								// merge selected options of sub product with the main product
								thisProduct.selectedOptions = jQuery.extend({}, thisProduct.selectedOptions, subproduct.selectedOptions);
								subproduct.selectedOptions.pid = tempPid;
								
								// if it is a product set then sub products can have their separate qty
								if (model.productSet) {
									tempQty += subproduct.selectedOptions.Quantity+comma;
								}
							}
						}
						
						if (model.productSet) {
							thisProduct.selectedOptions.Quantity = tempQty;
						}
						
						thisProduct.selectedOptions.pid = thisProduct.pid;
					}

					if (model.bundle) {
						thisProduct.selectedOptions.Quantity = 1; // hard coded qty=1 when we the product is a bundle
					}
					else if (!model.productSet){			
						var val = jQuery(thisProduct.containerId+" .quantityinput:last").val();
						if( val=='qty' ) val = 1;
						thisProduct.selectedOptions.Quantity = val;
					}

					if (model.productSet || thisProduct.selectedOptions.Quantity > 0) {
						
						// [AA] BUG: disabled="true" does not allow IE8 addtocart
						//addToCartBtn.attr("disabled", "true");
						
						var callback = function(){addToCartBtn.removeAttr("disabled");};
						if (model.source == 'cart') {
							thisProduct.selectedOptions.pliId = model.ID; // used in case of cart edit to replace existing line item
							callback = app.refreshCart;
						}
						
						var event = jQuery.Event("AddToCart");
						event.selectedOptions = thisProduct.selectedOptions;						
						
						if (isQuickViewFlag) {
							if ( typeof app.URLs.ajaxQuickViewAddProduct == 'undefined' || !app.URLs.ajaxQuickViewAddProduct )
								alert( "you need to defined the variable\napp.URLs.ajaxQuickViewAddProduct\nin your main template!");
							
							if (p2pEnabled) {
								var updateurl = app.util.appendParamToURL( app.URLs.ajaxHopupP2P, {'pid': thisProduct.selectedOptions.pid, "QuickView" : "true" } );
								jQuery("#pdpMain").load(updateurl, {}, function(response){});
							} else {
							var updateurl = app.util.appendParamToURL( app.URLs.ajaxQuickViewAddProduct, {'pid': thisProduct.selectedOptions.pid, "Quantity" : thisProduct.selectedOptions.Quantity, "QuickView" : "true" } );
							jQuery("#pdpMain").load(updateurl, {}, function(response){
								jQuery( thisProduct ).trigger( "AddedToCart" );
							});
							}
							
							
						} else {
							
							if (p2pEnabled) {
								var updateurl = app.util.appendParamToURL( app.URLs.ajaxHopupP2P, {'pid': thisProduct.selectedOptions.pid, "Quantity" : thisProduct.selectedOptions.Quantity } );
								app.quickView.show({url:updateurl});
							} else {
								if (jQuery.event.global["AddToCart"] == undefined || jQuery.event.global["AddToCart"] == null) {
									jQuery(".addtocart2").css("display", "block");
									jQuery(".addtocart").css("display", "none");
									jQuery('#brtn_pdp_cart_button2').css('cursor', 'auto');
									//window.setTimeout("jQuery('.addtocart2').css('display', 'none');jQuery('.addtocart').css('display', 'block');",2000);
									
									app.minicart.add( "", thisProduct.selectedOptions, callback );
									
								} else {
									jQuery(document).trigger(event);
								}
							}
						}
					}
					return false;
				} );

				return addToCartBtn;
			}

			var getQtyBox 		= function(thisProduct) {				
				
				jQuery(thisProduct.containerId+" .quantityinput:last").keyup(function(e){
					var val = null;
					try {
						val = parseInt(jQuery(thisProduct.containerId+" .quantityinput:last").val());
					} catch(e){val = null};

					if (val != null) {
						thisProduct.selectedOptions.Quantity = val;
						
						setAvailabilityMsg(createAvMessage(thisProduct, val));
						
						jQuery(thisProduct).trigger("AddtoCartEnabled");
					}
				});
				
				thisProduct.selectedOptions.Quantity = jQuery(thisProduct.containerId+" .quantityinput:last").val();
				setAvailabilityMsg(createAvMessage(thisProduct, thisProduct.selectedOptions.Quantity));
			}

			var getTabs 		= function(containerId) {

				var tabsDiv = jQuery(containerId+" #pdpTabsDiv");
				tabsDiv.tabs();

				// tab print handler
				jQuery("a.printpage").click(function() {
					window.print();
					return false;
				});
			}
			
			var getMiscLinks 	= function(thisProduct) {
			
				if ((model.master || model.variant) && thisProduct.selectedVar == null) {
					// disable wishlist/gift registry links for master products
					// jQuery( ".jn" ).append( "no selectedVar" );
					jQuery(thisProduct.containerId+" .addtowishlist, "+thisProduct.containerId+" .addtoregistry").addClass("unselectable");
					jQuery("#brtn_pd_wishlist_link").addClass("unselectable");
					
				}
				
				jQuery(thisProduct).bind("AddtoCartEnabled", {}, function(e, source){
					// enable wishlist/gift registry links for variant products
					
					var canSelect = allVariationsSelected();
					
					if ( source && "enabled" in source )
					{
						canSelect &= source.enabled;
					}

					if ( canSelect )
					{
						jQuery( 
								thisProduct.containerId + " #brtn_pdp_cart_button, " + 
								thisProduct.containerId + " #brtn_pd_cart_button, " + 
								thisProduct.containerId + " .addtowishlist, " + 
								thisProduct.containerId + " .addtoregistry").removeClass("unselectable");
								jQuery("#brtn_pd_wishlist_link").removeClass("unselectable");
					}
					else
					{
						// jQuery( this ).trigger( 'AddtoCartEnabled', {enabled:canSelect});
						jQuery( 
								thisProduct.containerId + " #brtn_pdp_cart_button, " +
								thisProduct.containerId + " #brtn_pd_cart_button, " + 
								thisProduct.containerId + " .addtowishlist, " + 
								thisProduct.containerId + " .addtoregistry").addClass("unselectable");
								jQuery("#brtn_pd_wishlist_link").addClass("unselectable");
					}
					// jQuery(thisProduct.containerId+" .addtowishlist, "+thisProduct.containerId+" .addtoregistry").removeClass("unselectable");
					
				});
				
				// jQuery("#brtn_pd_wishlist_link").click( function () { 
				jQuery(thisProduct.containerId+" .addtowishlist a, "+thisProduct.containerId+" .addtoregistry a").click(function(e) {
					// inserted by JN
					/*
					 * We have a small problem here:  The ref app only  
					 * changes the selected variation is color and size
					 * are selected.  Therefore the previous test of the
					 * thisProduct.selectedVar will always be good.
					 * the code further down responsible for this is this line:
					 * if (this.selectedIndex == 0) { return; }
					 * But if you remove that line, the ref app assumes that 
					 * there is no variant available!  All color swatches will
					 * be masked :-(  I assume the behavior for ref app works
					 * opposite to Burton:  Burton: 1st color then size; Ref app
					 * 1st size and then color.
					 * Hence I put in here a small test.  we should always have
					 * a size dropdown with that ID
					 * 
					 *  OK, we need to narrow it down further more:
					 *  If we have a drop down field, the selected value has to match the
					 *  the value of the currently selected attribute 
					 */
					if ( !allVariationsSelected() )
					{
						return false;
					}
					prepareAddToWishList( thisProduct.selectedVar.id, jQuery(".quantityinput").val() ); 
				} );

				/*
				// DUPLICATE
				// Add to wishlist, Add to gift registry click handler
				jQuery(thisProduct.containerId+" .addtowishlist a, "+thisProduct.containerId+" .addtoregistry a").click(function(e) {
					// append the currect selectied options to the url
					
					// create a local copy of the selected options
					var selectedOptions = jQuery.extend({}, {}, thisProduct.selectedOptions);
					if (model.master || model.variant) {
						if (thisProduct.selectedVar != null) {
							selectedOptions.pid = thisProduct.selectedVar.id;
						}
						else {
							return false; // do not allow master product to be added to gift registry/wishlist
						}
					}
					else {
						selectedOptions.pid = thisProduct.pid;
					}
					
					var tempUrl = this.href;
					
					if (!(tempUrl.indexOf("?") > 0)) {
						tempUrl = tempUrl + "?";
					}
					// serialize the name/value into url query string and append it to the url, make request
					window.location = tempUrl + "&" + jQuery.param(selectedOptions);
					return false;
				} );			
				*/
				jQuery(thisProduct.containerId+" #pdpSendToAFriend").click(function(e) {
						if (thisProduct.selectedVar != null ){
							
							//alert("NOT NULL: "+ app.URLs.sendToFriend + thisProduct.selectedVar.id );
						app.dialog.open(app.URLs.sendToFriend + thisProduct.selectedVar.id, app.resources.SEND_TO_FRIEND,'',{innerHeight: 523,innerWidth: 560, outerHeight: 523, outerWidth: 560});
						} else {
							//alert("NULL: "+ app.URLs.sendToFriend + thisProduct.pid + app.URLs.variationColorAttr + jQuery('.emptyswatch.selected').children().attr('value') );
							app.dialog.open(app.URLs.sendToFriend + thisProduct.pid + app.URLs.variationColorAttr + jQuery('.emptyswatch.selected').children().attr('value'), app.resources.SEND_TO_FRIEND,'',{innerHeight: 523,innerWidth: 560, outerHeight: 523, outerWidth: 560});
						}
					return false;
				} );
			}
			
			var getRatingSection = function(containerId) {

				jQuery(containerId+" #pdpReadReview").click(function(e) {
					jQuery(containerId+" #pdpTabsDiv").tabs("select", "pdpReviewsTab");
				} );

				jQuery(containerId+" #pdpWriteReview").click(function(e) {
				} );
			}

			var getAskAndAnswerSection = function(containerId) {

				jQuery(containerId+" #pdpReadAA").click(function(e) {
					jQuery(containerId+" #pdpTabsDiv").tabs("select", "pdpAATab");
				} );

				jQuery(containerId+" #pdpWriteAA").click(function(e) {
				} );
			}
			
			// based on availability status, creates a message
			// param val - the stock value to compare i.e. qty entered by user
			var createAvMessage = function(thisProduct, val) {
					
				var avStatus 	= thisProduct.getAvStatus(); // availability status
				var avMessage 	= app.resources[avStatus];
				var ats 		= thisProduct.getATS(); // get available to sell qty
				
				if (avStatus === app.constants.AVAIL_STATUS_BACKORDER) {						
					avMessage = avMessage + "<br/>" + jQuery.format(app.resources["IN_STOCK_DATE"], (new Date(thisProduct.getInStockDate())).toDateString() );
				}
				else if (val > ats && avStatus !== app.constants.AVAIL_STATUS_NOT_AVAILABLE) {
					// display quantity left message
					avMessage = jQuery.format(app.resources["QTY_"+avStatus], ats);

					//avMessage += ", " + jQuery.format(app.resources["REMAIN_"+avStatus], val - model.ATS);						
				}
				
				return avMessage;
			}

			var setAvailabilityMsg = function(msg) {
				jQuery(myContainerId+" .availability:last .value").html(msg);
			}

			var computePrice = function(thisProduct) {

				var price = thisProduct.selectedVar != null ? thisProduct.selectedVar.pricing.sale : model.pricing.sale;
				// calculate price based on the selected options prices
				jQuery.each(thisProduct.selectedPrice, function(){
					price = (new Number(price) + new Number(this)).toFixed(2);
				});

				return price;
			}

			// bind click handlers for prev/next buttons on pdp from search
			var getNavLinks = function() {
				// bind events
				jQuery(".productnavigation a").click(function(e) {
					app.getProduct({url: this.href, source: "search"});
					return false;
				});
			}
			
			// size chart link click binding
			var getSizeChart = function() {
				jQuery(".sizeChartLink").click(function(e){
					if (jQuery("#sizeChartDialog").length == 0) {
						jQuery("<div/>").attr("id", "sizeChartDialog").appendTo(document.body);
					}
					
					app.createDialog({id: 'sizeChartDialog', options: {
				    	height: 530,
				    	width: 800,
				    	title: 'Size Chart'
					}});
					
					jQuery('#sizeChartDialog').dialog('open');
					
					jQuery("#sizeChartDialog").load(this.href);
					
					return false;
				});
			}
			
			// Product instance
			return {
				pid					: model.ID,
				variant				: model.variant,
				master				: model.master,
				bundled				: model.bundled,
				selectedVarAttribs	: {},
				varAttributes		: {},
				selectedVar			: null,
				selectedOptions		: {}, // holds currently selected options object {optionName, selected val}
				selectedPrice		: {}, // holds price for selected options
				containerId			: null, // holds html container id of this product
				subProducts			: [], // array to keep sub products links 

				showSelectedVarAttrVal: function(varId, val) {
					jQuery(this.containerId+" .variation_attributes div span[id='pdp"+varId+"selected']").html(val);
				},
				
				readReviews: function() {
					jQuery(this.containerId+" #pdpTabsDiv").tabs("select", "pdpReviewsTab");
				},
				
				readAskAndAnswer: function() {
					jQuery(this.containerId+" #pdpTabsDiv").tabs("select", "pdpAATab");
				}, 
				
				// shows product images and thumbnails
				// @param selectedVal - currently selected variation attr val
				// @param vals - total available variation attr values
				showImages: function(selectedVal, vals)  {
					var that = this;
					vals = vals || {};
					
					// show swatch related images for the current variation value					
					jQuery.each(vals, function(){
						var imgCounter = -1;
						var thisVal = this;
						if (this.val === selectedVal && this.images) {
							if (this.images.small.length > 0) {
								jQuery(that.containerId+" .product_thumbnails:last").html("");
								jQuery(that.containerId+" .product_image").html("").append(jQuery("<img/>").attr("src", thisVal.images.large[0]));
							}
							// make sure to show number of images based on the smallest of large or small as these have to have 1-1 correspondence.
							var noOfImages = this.images.large.length >= this.images.small.length ? this.images.small.length : this.images.large.length;
							
							jQuery.each(this.images.small, function(){
								imgCounter++;
								var imageInd = imgCounter;
								if (imgCounter > noOfImages - 1) {
									return;
								}
								jQuery(that.containerId+" .product_thumbnails:last").append(jQuery("<img/>").attr("src", this).hover(function(e){
									jQuery(that.containerId+" .product_image").html("").append(jQuery("<img/>").attr("src", thisVal.images.large[imageInd]));
								}));
							});
						}
					});
				},

				/**
				* Event handler when a variation attr is selected.
				*/
				varAttrSelected: function(e) {
					var thisProduct = this;
					// update the selected value node
					// the text: "Selected Color: True Black"
					this.showSelectedVarAttrVal(e.data.id, e.data.val);
					
					var ret = null;
					if ( e.data.id in this.selectedVarAttribs)
						ret = this.selectedVarAttribs[e.data.id];
					this.selectedVarAttribs[e.data.id] = e.data.val;				
					
					// store this ref
					var that = this;

					// trigger update event which will update every other variation attribute i.e. enable/disable etc.

					// first reset the contents of each attribute display
					// when we have got the varriations data
					if (!isLoadingVar) {
						jQuery.each(model.variations.attributes, function () {
							if (this.id != e.data.id) {
								if ( jQuery(that.containerId+" select#pdp"+this.id + "var" ).length == 1)
								{
									// this object is shown as a drop down. 
									jQuery.each( jQuery(that.containerId+" select#pdp"+this.id + "var option" ), function(){
										var dataa = jQuery(this).parent().data("data");
										// find A variation with this val^
										if ( !empty( this.value ) ) // test only if we have value
										{
											if (that.isVariation({id:e.data.id, val:e.data.val}, {id:dataa.id, val:this.value })) {
												// found at least 1 so keep it enabled
												jQuery(this).removeClass("unselectable");
												jQuery(this).attr( "disabled", false );
											}
											else
											{
												// if this option was the selected one we 
												// need to deselect this one
												var wasSel = jQuery( this ).attr( 'selected' );
												jQuery(this).addClass("unselectable");
												jQuery(this).removeClass("selected");
												jQuery(this).attr( "disabled", true );
												// deselect in case it was selected and is no longer available 
												if ( wasSel )
												{
													jQuery( this ).parent().val( '' );
													jQuery( thisProduct ).trigger( 'AddtoCartEnabled', {enabled:false});
												}
											}
										}
									});
								}
								else
								{
									// I have no idea how this is shown, let's assume it is in LIs and anchors
									jQuery.each(jQuery(that.containerId+" #pdp"+this.id+"var li a"), function(){
										var dataa = jQuery(this).data("data");
										// find A variation with this val
										if (that.isVariation({id:e.data.id, val:e.data.val}, {id:dataa.id, val:this.innerHTML})) {
											// found at least 1 so keep it enabled
											jQuery(this).parent().removeClass("unselectable");
										}
										else
										{
											// those are the colors:  They are never unselectable for Burton!
											// jQuery(this).parent().addClass("unselectable");
											jQuery(this).parent().removeClass("selected");
										}
									});
								}
							}
							else {
								// show swatch related images for the current value								
								that.showImages(e.data.val, this.vals);
							}
						});

						// find a matching variation and update the screen
						this.selectedVar = this.findVariation(this.selectedVarAttribs);
						jQuery("#brtn_qv_error_text, #brtn_pdp_error_text").hide();
					}

					// lets fire refresh view event to enable/disable variations attrs
					jQuery(this).trigger("VariationsLoaded");
					return ret;
				},

				/**
				* go thru all variations attr and disable which are not available
				*/
				resetVariations: function() {
					if (isLoadingVar) {
						return ; // we don't have the complete data yet
					}
					var that = this;
					
					jQuery.each(model.variations.attributes, function () {
						jQuery.each(jQuery(that.containerId+" #pdp"+this.id+"var li a"), function(){
							var dataa = jQuery(this).data("data");
							// find A variation with this val
							if (that.isVariation({id:dataa.id, val:this.innerHTML})) {
								// found at least 1 so keep it enabled
								jQuery(this).parent().removeClass("unselectable");
							}
							else {
								jQuery(this).parent().addClass("unselectable");
								jQuery(this).parent().removeClass("selected");
							}
						});
					});
				},

				refreshView: function() {
					
					// mark not purchasable variations
					// switched to setting the style instead of class - doesn't function 100% properly in IE
					var that = this;
					jQuery.each(model.variations.variants, function () {
						if (typeof(that.selectedVarAttribs) != 'undefined' && that.selectedVarAttribs.variationColor == this.attributes.variationColor) {
							if (this.avStatus === app.constants.AVAIL_STATUS_NOT_AVAILABLE) {
								jQuery("option.[value='" + this.attributes.variationSize + "']").css("color","red"); ;
								//jQuery("option.[value='" + this.attributes.variationSize + "']").removeClass("purchasable");
							} 
							else {
								//jQuery("option.[value='" + this.attributes.variationSize + "']").addClass("purchasable");
								jQuery("option.[value='" + this.attributes.variationSize + "']").css("color","black"); ;
							}
						}
					});
					
					
					
					
					var thisProduct = this;
					
					if (!isLoadingVar && this.selectedVar == null) {
						// if we have loaded the variations data then lets if the user has already selected some values
						// find a matching variation
						this.selectedVar = this.findVariation(this.selectedVarAttribs);
					}
				
					if ((p2pEnabled || eCommerceEnabled) && !isLoadingVar && this.selectedVar != null) {
						// update availability
						setAvailabilityMsg(createAvMessage(thisProduct, 1));
						// update price
						
						if (!p2pEnabled) this.showUpdatedPrice(this.selectedVar.pricing.sale, this.selectedVar.pricing.standard);
						
						if (!(!this.selectedVar.inStock && this.selectedVar.avStatus === app.constants.AVAIL_STATUS_NOT_AVAILABLE)) {
							// enable add to cart button
							jQuery(this.containerId+" .addtocart").css("display", "block");
							jQuery(this.containerId+" .comingsoon:last").css("display", "none");
							jQuery(this.containerId+" .soldout:last").css("display", "none");
							jQuery(this).trigger("AddtoCartEnabled", {enabled:true} );
							jQuery(".quantityinput").removeAttr("disabled");
						}
						else {
							jQuery(this.containerId+" .addtocart").css("display", "none");
							if (this.selectedVar.backorderable) {
								jQuery(this.containerId+" .comingsoon:last").css("display", "block");
								jQuery(this.containerId+" .soldout:last").css("display", "none");
							}
							else {
								jQuery(this.containerId+" .comingsoon:last").css("display", "none");
								jQuery(this.containerId+" .soldout:last").css("display", "block");
							}
							jQuery(".quantityinput").attr("disabled", "true");
							jQuery(this).trigger("AddtoCartEnabled", {enabled:false} );
						}
					}
					else {
						if (isLoadingVar) {
						// update availability
							setAvailabilityMsg(app.showProgress("productloader"));
						}
						else {
							setAvailabilityMsg(app.resources["NON_SELECTED"]);
						}
						// disable add to cart button
						// BUG with IE8, so out:
						//jQuery(this.containerId+" .addtocart_button:last").attr("disabled", "true");
					}
					
					var nonSelectedVars = [];
					
					// update selected var attr vals
					jQuery.each(model.variations.attributes, function(){
						thisProduct.showSelectedVarAttrVal(this.id, thisProduct.selectedVarAttribs[this.id]);
						
						if (!thisProduct.selectedVarAttribs[this.id] || thisProduct.selectedVarAttribs[this.id] == "" ) {
							nonSelectedVars.push(this.name);
						} 
					});
					
					// process non-selected vals and show updated tooltip for A2C button as a reminder
					var tooltipStr = nonSelectedVars.join(" & ");
					
					if (nonSelectedVars.length > 0) {
						var availMsg = jQuery.format(app.resources["MISSING_VAL"], tooltipStr);
						setAvailabilityMsg(availMsg);
						jQuery(thisProduct.containerId+" .addtocart_button:last").attr("title", availMsg);
					}					
				},

				showUpdatedPrice: function(sale, standard) {
					standard = standard || 0;
					
					sale = (new Number(sale)).toFixed(2);
					standard = (new Number(standard)).toFixed(2);
					
					
					var priceHtml = '<span class="brtn_sales_price">' + app.currencyCodes[model.pricing.currencyCode] + sale + '</span>';
					if (standard > 0 && standard > sale) {
						// if we have different prices...
						priceHtml = '<span class="brtn_old_price" style="text-decoration: line-through;">'
							+ app.currencyCodes[model.pricing.currencyCode] + standard 
							+ '</span>&nbsp;&nbsp' + priceHtml;
					}
					priceHtml = '<div id="brtn_price" style="text-decoration: none">' + priceHtml + '</div>';
					
					// original code
					/*
					var priceHtml = '<div id="brtn_qv_saleprice">' + app.currencyCodes[model.pricing.currencyCode] + sale + '</div>';
					
					if (standard > 0 && standard > sale) {
						// show both prices
						priceHtml = '<div id="brtn_qv_price">' + app.currencyCodes[model.pricing.currencyCode] + standard + '</div>' + priceHtml;
					}
					*/					
					
					jQuery(this.containerId+" .product_information .price:first").html(priceHtml);
					// containerId contains #, get rid of it before finding the right price div
					jQuery(this.containerId+" #pdpATCDiv"+this.containerId.substring(1)+" .price").html(priceHtml);
				},

				optionSelected: function(e) {
					this.selectedOptions[e.data.id] = e.data.val;
					this.selectedPrice[e.data.id] = e.data.price;

					// update price and show
					this.showUpdatedPrice(computePrice(this), model.pricing.standard);
				},

				getPrice: function() {
					return computePrice(this);
				},

				/*
				* receives 2 or 1 var attrib values and tries to figure out if there is a variant with these values.
				* returns true/false
				*/
				isVariation: function(val1, val2) {
					var variant = null;

					for (var i=0; i<model.variations.variants.length; i++) {
						variant = model.variations.variants[i];
						if (variant.attributes[val1.id] == val1.val && (val2 == undefined || variant.attributes[val2.id] == val2.val)) {
							return true;
						}
					}
					/*
					 * apparently there is no way to break out of jQuery.each half way :(
					jQuery.each(model.variations.variants, function(){
						if (!found && this.attributes[val1.id] == val1.val && this.attributes[val2.id] == val2.val) {
							found = true;
							return;
						}
					});*/
					return false;
				},

				/*
				* find a variant with the given attribs object
				* return null or found variation json
				*/
				findVariation: function(attrs) {
					if (!this.checkAttrs(attrs)) {
						return null;
					}

					var attrToStr = function(attrObj) {
						var result = "";
						jQuery.each(model.variations.attributes, function(){
							result += attrObj[this.id];
						});
						return result;
					}

					var attrsStr = attrToStr(attrs);

					for (var i=0; i<model.variations.variants.length; i++) {
						variant = model.variations.variants[i];
						if (attrToStr(variant.attributes) === attrsStr) {
							return variant;
						}
					}
					return null;
				},

				findVariationById: function(id) {

					for (var i=0; i<model.variations.variants.length; i++) {
					// IE7 does NOT support this!!!
					//for each(var variation in model.variations.variants) {
						var variation = model.variations.variants[i];
						if (variation && variation.id === id) {
							return variation;
						}
					}

					return {};
				},

				/*
				* see if the specified attrs object has all the variation attributes present in it
				* return true/false
				*/
				checkAttrs: function(attrs) {
					for (var i=0; i<model.variations.attributes.length; i++) {
						if (attrs[model.variations.attributes[i].id] == null) {
							return false;
						}
					}
					return true;
				},
				
				// given an id, return attr definition from model.variations.attributes
				getAttrByID: function(id) {
					for (var i=0; i<model.variations.attributes.length; i++) {
						if (model.variations.attributes[i].id === id) {
							return model.variations.attributes[i];
						}
					}
					return {};
				},
				
				// returns current availability status e.g. in_stock, preorder etc.
				getAvStatus: function() {
					if ((this.variant || this.master) && this.selectedVar != null) {
						return this.selectedVar.avStatus;
					}
					else {
						return model.avStatus;
					}
				},
				
				// return available to sell qty
				getATS: function() {
					if ((this.variant || this.master) && this.selectedVar != null) {
						return this.selectedVar.ATS;
					}
					else {
						return model.ATS;
					}
				},
				
				// returns in stock date 
				getInStockDate: function() {
					if ((this.variant || this.master) && this.selectedVar != null) {
						return this.selectedVar.inStockDate;
					}
					else {
						return model.inStockDate;
					}
				},
				
				// determine if A2C button is enabled or disabled
				// true if enabled, false otherwise
				isA2CEnabled: function() {
					if (this.variant || this.master) {
						if (this.selectedVar != null) {
							return this.selectedVar.avStatus === app.constants.AVAIL_STATUS_IN_STOCK;
						}
						else {
							return false;
						}
					}
					else {
						return model.avStatus === app.constants.AVAIL_STATUS_IN_STOCK;;
					}
				},

				show: function(options) {
					// preserve this instance
					var thisProduct = this;

					// bind events
					jQuery(this).bind("VariationsLoaded", {}, function(e, source){
						if (thisProduct.variant && thisProduct.selectedVar == null) {
							thisProduct.selectedVar = thisProduct.findVariationById(thisProduct.pid);
							thisProduct.selectedVarAttribs = thisProduct.selectedVar == null ? {} : jQuery.extend({}, {}, thisProduct.selectedVar.attributes);
						}
						// enable/disable unavailable values
						if (source && source == "loadVariants") {
							thisProduct.resetVariations();
						}
						thisProduct.refreshView();
					});

					this.containerId 	= "#"+options.containerId;
					var container		= jQuery(this.containerId);
					var append			= options.append;
					var isQuickView 	= false;

					if (options.source && options.source == "quickview") {
						isQuickView = true;
					}

					if (append) {
						this.containerId = "#"+this.pid+"Div";
					}
					myContainerId = this.containerId;
					
					// bind click handlers for prev/next links
					getNavLinks();
					
					// size chart click binding
					getSizeChart();

					// variation attributes
					if (model.master || model.variant) {
						loadVariants(this); // make a server call to load the variants, this is due to the performance reasons
						// Certain Burton products, such as snowboards, have only variationSize and not variationColor.
						// For these products, color swatches are driven by variationSize, so override default colorAttrib value.
						if (model.variations.attributes.length == 1 && model.variations.attributes[0].id == "variationSize") {
							colorAttrib = "variationSize";
						}
						// meanwhile display the available variation attributes
						jQuery.each(model.variations.attributes, function(){

							var thisAttr = this;

							thisProduct.varAttributes[this.id] = {};

							if (this.ui == 0) {  // drop downs
								var ele = jQuery(thisProduct.containerId + " #pdp"+this.id+"var")
								if (ele[0].selectedIndex >= 0 && ele[0].options[ele[0].selectedIndex].value != "") {
									// grab the currently selected val
									thisProduct.selectedVarAttribs[this.id] = ele[0].options[ele[0].selectedIndex].value;
								}
								// default ui i.e. drop down
								ele.data("data", {id: this.id, val: ''}).change(function(e){
										if (this.selectedIndex == 0)
										{
											jQuery(" .addtocart").css("display", "block");
											jQuery(" .comingsoon:last").css("display", "none");
											jQuery(" .soldout:last").css("display", "none");
											jQuery(thisProduct).trigger("AddtoCartEnabled", {enabled:false} );
											return;
										}

										e.data = jQuery(this).data("data");
										e.data.val = this.options[this.selectedIndex].value;
										thisProduct.varAttrSelected(e);
									});
							}
							else {       // color swatches
								// color, width, size
								// its a custom ui with div controlled via css
								var pdpVarId = this.id;
								// grab the currently selected attr val
								thisProduct.selectedVarAttribs[pdpVarId] = jQuery(thisProduct.containerId + " #pdpVarAttrDiv #pdp"+pdpVarId+"var .selected a").html();								
								
								var varEventHandler = function(e){
									var thisObj = jQuery(this);

									// check if this color isn't already selected.  if so,
									// just return
									if (thisObj.parent().hasClass("selected") ||
										thisObj.parent().hasClass("unselectable")) {
										return false;
									}

									e.data = {id: pdpVarId, val: this.innerHTML, valId: thisObj.attr( 'value' ) };

									// remove the current selection
									jQuery(thisProduct.containerId + " #pdpVarAttrDiv #pdp"+pdpVarId+"var .selected").removeClass("selected");
									
									// mark this as the newly selected image 
									thisObj.parent().addClass("selected");
									// deselect all unavailable colors
									var oldVal = thisProduct.varAttrSelected(e);
									e.data["oldVal"] = oldVal;
									
									// lets fire refresh view event to enable/disable variations attrs
									// alert( thisProduct );
									jQuery( thisProduct ).trigger("variationChanged", [e.data] );
									return false;
								}
								
								var varJqryObjs = jQuery(thisProduct.containerId + " #pdp"+pdpVarId+"var a");
								// if its a color attr then render its swatches
								if (pdpVarId === colorAttrib) {
									var colorAttrDef = thisProduct.getAttrByID( colorAttrib );
									varJqryObjs.each(function(){
									
										// given a variation attr value, find its swatch image url
										var findSwatch = function(val) {
											for (var i=0; i<colorAttrDef.vals.length; i++){
												if (colorAttrDef.vals[i].val === val) {													
													return colorAttrDef.vals[i].images.swatch;
												}
											}
											return ""; // no swatch image found
										}
										
										var swatchUrl = findSwatch(this.innerHTML); // find swatch url
										
										if (swatchUrl && swatchUrl != "") {
											jQuery(this).css("color", "transparent").parent().css("background", "url(" + swatchUrl + ")");
										}
										else {
											jQuery(this).css("color", "transparent"); // no swatch image found
										}
									});
									
									varJqryObjs.data("data", {id: pdpVarId}).click(varEventHandler).hover(function(e){
										thisProduct.showSelectedVarAttrVal( colorAttrib, this.innerHTML);										
										thisProduct.showImages(this.innerHTML, colorAttrDef.vals)
									}).mouseleave(function(e) {
										if (thisProduct.selectedVarAttribs[ colorAttrib ]) {
											thisProduct.showImages(thisProduct.selectedVarAttribs[ colorAttrib ], colorAttrDef.vals)
										}
										else {
											thisProduct.showImages("", [{val: "", images: model.images}]);
										}
										
										thisProduct.showSelectedVarAttrVal( colorAttrib, thisProduct.selectedVarAttribs[colorAttrib] || "");
									});
								}
								else {								
									varJqryObjs.data("data", {id: pdpVarId}).click(varEventHandler);
								}
							}
						});
						
						if (thisProduct.selectedVarAttribs[colorAttrib]) {
							// show swatch related images for the current value								
							thisProduct.showImages(thisProduct.selectedVarAttribs[colorAttrib], thisProduct.getAttrByID( colorAttrib ).vals);
						}
						else {
							// show images and bind hover event handlers for small/thumbnails to toggle large image								
							thisProduct.showImages("", [{val: "", images: model.images}]);
						}
					}
					else {
						// show images and bind hover event handlers for small/thumbnails to toggle large image								
						thisProduct.showImages("", [{val: "", images: model.images}]);
					}
					
					// bind product options event(s)
					getOptionsDiv(this);

					if(!model.productSet) {
						// quantity box
						if (!model.bundle) {
							getQtyBox(this);
						}// update avaiability for a bundle product, for everything else its done inside getQtyBox
						else if (model.bundle) {
							setAvailabilityMsg(createAvMessage(this, 1));
						}
					}

					// Add to cart button
					var addToCartBtn = getAddToCartBtn(this,isQuickView);
					if (model.master || model.variant || model.productSet || model.bundle || (!model.inStock && model.avStatus === app.constants.AVAIL_STATUS_NOT_AVAILABLE && !model.productSet)) {
						// BUG IE8,so out:
						//addToCartBtn.attr("disabled", "true");
						jQuery(".quantityinput").attr("disabled", "true");
					}
																			
					if (model.bundle) {
						// if the bundled products are standard prodcuts then determine disability of the a2c button by checking each producgt's availability
						var bundleA2CEnabled = false;
						for (var i = 0; i < thisProduct.subProducts.length; i++) {
							var subProduct = thisProduct.subProducts[i];
							bundleA2CEnabled = subProduct.isA2CEnabled();
							if (!bundleA2CEnabled) {
								break;
							}
						}
						if (!bundleA2CEnabled) {
							//BUG IE8, so out
							//addToCartBtn.attr("disabled", "true");
						} 
						else {
							addToCartBtn.removeAttr("disabled");
							jQuery(".quantityinput").removeAttr("disabled");
						}
					}						

					if (!model.subProduct && !model.bundled) {

						if (!model.productSet && !isQuickView && !model.bundle) {
							// customer rating
							getRatingSection(this.containerId);							
						}
					}
					
					// wish list, sent to friend, add to gift
					getMiscLinks(this);
							
					// recommendations carosel
					loadRecommendations(this.containerId);

					// tabs
					getTabs(this.containerId);										
					
					// see if have any subproducts and bind AddtoCartEnabled event
					jQuery.each(thisProduct.subProducts, function(){
						jQuery(this).bind("AddtoCartEnabled", {},
							/**
							* Event handler when a subproduct of a product set or a bundle is selected.
							* Basically enable the add to cart button or do other screen refresh if needed like price etc.
							*/
							function() {
								// enable Add to cart button if all the sub products have been selected
								var enableAddToCart = true;
								var subProducts = thisProduct.subProducts;
								var price = new Number();

								for (var i = 0; i < subProducts.length; i++) {
									if (((subProducts[i].variant || subProducts[i].master) && subProducts[i].selectedVar == null) ||
										(!subProducts[i].bundled && (subProducts[i].selectedOptions["Quantity"] == undefined ||
										subProducts[i].selectedOptions["Quantity"] <= 0))) {
										enableAddToCart = false;
										break
									}
									else {
										if (subProducts[i].selectedVar != null) {
											subProducts[i].selectedOptions.pid = subProducts[i].selectedVar.pid;
										}
										else {
											subProducts[i].selectedOptions.pid = subProducts[i].pid;
										}

										price = price + new Number(subProducts[i].getPrice());
									}
								}

								if (enableAddToCart && (model.productSet || model.inStock)) {
									jQuery(thisProduct.containerId+" .addtocart_button:last").removeAttr("disabled");

									// show total price
									thisProduct.showUpdatedPrice(price);
								}
								else {
									// BUG IE8, so out:
									//jQuery(thisProduct.containerId+" .addtocart_button:last").attr("disabled", "true");
								}
							}
						);
					});
				},

				toString: function() {
					return this.model;
				}
			}
		} // Product defintion end
	}
	else {
		// dw namespace has not been defined yet
		alert("app namespace is not loaded yet!");
	}
})(app);
					 
function empty( val )
{
	if ( val )
		return false;
	return true;
}

var allVariationsSelected = function(){
	return 	(	
			// boards don't have color selection!
			jQuery( 'ul#pdpvariationColorvar').length == 0 
			||
			jQuery( '#pdpvariationColorvar  li.selected').length > 0
		)
		&&
		(	// if we have a drop down, this needs to be selected
			jQuery( 'select#pdpvariationSizevar').length == 0 
			||
			jQuery( '#pdpvariationSizevar').val()   // we need to have a value ID
		)
		&&
		(	// if we have swatches, we need a selected one
			jQuery( 'ul#pdpvariationSizevar').length == 0 
			||
			jQuery( '#pdpvariationSizevar  li.selected').length > 0
		)
}

