(function(app){
	if (app) {
		// add Product object to dw namespace
		app.Product = function(response) {
			// product private data

			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.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"]);
					}
				});
			}

			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 disableAddToCart = function(thisProduct) {
				jQuery(thisProduct.containerId+" div.addtocart .addtocartBtn").attr("disabled", "disabled");
				jQuery(thisProduct.containerId+" div.addtocart").addClass("disabled");
			};
			
			var enableAddToCart = function(thisProduct) {
				jQuery(thisProduct.containerId+" div.addtocart .addtocartBtn").attr("disabled", null);
				jQuery(thisProduct.containerId+" div.addtocart").removeClass("disabled");
			};
			
			// We don't use this
			var getAddToCartBtn = function(thisProduct) {
				var addToCartBtn = jQuery(thisProduct.containerId+" .addtocartBtn:last").click(function(e) {
					if (model.master || model.variant) {
						if (thisProduct.selectedVar == null) {
							return false;
						}
						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){
						thisProduct.selectedOptions.Quantity = jQuery(thisProduct.containerId+" .quantityinput:last").val();
					}

					if (model.productSet || thisProduct.selectedOptions.Quantity > 0) {
						disableAddToCart(thisProduct);
						var callback = function(){enableAddToCart(thisProduct)};
						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;						
						
						// close the quick view when user clicks A2C.
						app.quickView.close();
												
						(jQuery.event.global["AddToCart"] == undefined || jQuery.event.global["AddToCart"] == null) ? app.minicart.add( "", thisProduct.selectedOptions, callback ) : 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");
					}
				});
				if( thisProduct.variant ) {
					thisProduct.selectedOptions.Quantity = 1;
				} else {
					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(thisProduct.containerId+" .addtowishlist, "+thisProduct.containerId+" .addtoregistry").addClass("unselectable");
				}
				
				jQuery(thisProduct).bind("AddtoCartEnabled", {}, function(e, source){
					// enable wishlist/gift registry links for variant products
					jQuery(thisProduct.containerId+" .addtowishlist, "+thisProduct.containerId+" .addtoregistry").removeClass("unselectable");
				});
				
				// 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) {
					app.dialog.open(app.URLs.sendToFriend, app.resources.SEND_TO_FRIEND);
					return false;
				} );
			}
			
			var getRatingSection = function(containerId) {

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

				jQuery(containerId+" #pdpWriteReview").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");
				},
				// 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.thumbnail.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.thumbnail.length ? this.images.thumbnail.length : this.images.large.length;
							
							jQuery.each(this.images.thumbnail, function(){
								imgCounter++;
								var imageInd = imgCounter;
								if (imgCounter > noOfImages - 1) {
									return;
								}
								jQuery(jQuery(that.containerId+" .thumb_view li")[imageInd]).mouseenter(function(e){
									jQuery(this).addClass('hover');
								}).mouseleave(function(){
									jQuery(this).removeClass('hover');
								}).click(function(){
									jQuery(that.containerId+" .product_image img").attr("src", thisVal.images.large[imageInd]);
								});
							});
						}
					});
				},

				/**
				* Event handler when a variation attr is selected.
				*/
				varAttrSelected: function(e) {
					// update the selected value node
					this.showSelectedVarAttrVal(e.data.id, e.data.val);

					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) {
								jQuery.each(jQuery(that.containerId+" #pdp"+this.id+"var li a"), function(){
									var dataa = jQuery(this).data("data");
									if( !dataa ) {
										
									} else {
										// find A variation with this val
										var val = $(this).attr("title");
										if (that.isVariation({id:e.data.id, val:e.data.val}, {id:dataa.id, val:val})) {
											// found at least 1 so keep it enabled
											jQuery(this).parent().removeClass("unselectable");
										}
										else {
											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);
					}

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

				/**
				* 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
							var li = null;
							if( dataa ){ 
								var val = $(this).attr('title');
							
								if (that.isVariation({id:dataa.id, val:val})) {
									// found at least 1 so keep it enabled
									li = jQuery(this.parentNode);
									li.removeClass("unselectable");
								}	else {
									li = jQuery(this.parentNode);
									li.addClass("unselectable");
									li.removeClass("selected");
								}
							}
						});
					});
				},

				refreshView: function() {
					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( app.ProductCache.variant ) return;
					
					if (!isLoadingVar && this.selectedVar != null) {
						// update availability
						setAvailabilityMsg(createAvMessage(thisProduct, 1));
						// update price
						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
							enableAddToCart(thisProduct);
							jQuery(this).trigger("AddtoCartEnabled");
						}
						else {
							disableAddToCart(thisProduct);
						}
					}
					else {
						if (isLoadingVar) {
						// update availability
							setAvailabilityMsg(app.showProgress("productloader"));
						}
						else {
							setAvailabilityMsg(app.resources["NON_SELECTED"]);
						}
						// disable add to cart button
						disableAddToCart(thisProduct);
					}
					
					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+" .addtocartBtn: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 = '<div class="salesprice">' + app.currencyCodes[model.pricing.currencyCode] + sale + '</div>';
					
					if (standard > 0 && standard > sale) {
						// show both prices
						priceHtml = '<div class="standardprice">' + app.currencyCodes[model.pricing.currencyCode] + standard + '</div>' + priceHtml;
					}					
					
					jQuery(this.containerId+" .productdetail-box .pricing: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, found = false;

					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)) {
							found = true;
							//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 found;
				},

				/*
				* 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 && model.variations.variants.length>1; 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
						// meanwhile display the available variation attributes
						jQuery.each(model.variations.attributes, function(){

							var thisAttr = this;

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

							var pdpVarId = this.id;
							var singleValue = jQuery(thisProduct.containerId + " #pdpVarAttrDiv input#pdp"+pdpVarId+"var");
							
							if( singleValue.size()==1 ) {
								var e = {'data' : { 'id' : pdpVarId, 'val':singleValue.val() } };
								thisProduct.varAttrSelected(e);								
							} else if( this.ui == 0 ) {
								var ele = jQuery(thisProduct.containerId + " #pdp"+this.id+"var")
								if(ele[0] && 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
								if( ele ) {
									ele.data("data", {id: this.id, val: ''}).change(function(e){
										if (this.selectedIndex == 0) { return; }

										e.data = jQuery(this).data("data");
										e.data.val = this.options[this.selectedIndex].value;
										thisProduct.varAttrSelected(e);
									});
								}
								
							} else {
								// 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").attr("title");								
								
								var varEventHandler = function(e){
									var thisObj = jQuery(this);
									
									if (thisObj.parent().hasClass("selected") ||
										thisObj.parent().hasClass("unselectable")) {
										return false;
									}
									
									var val = $(this).attr("title");
									e.data = {id: pdpVarId, val: val};

									// remove the current selection
									jQuery(thisProduct.containerId + " #pdpVarAttrDiv #pdp"+pdpVarId+"var .selected").removeClass("selected");

									thisObj.parent().addClass("selected");
									thisProduct.varAttrSelected(e);
									return false;
								}
								
								var varJqryObjs = jQuery(thisProduct.containerId + " #pdp"+pdpVarId+"var a");
								// if its a color attr then render its swatches
								var colorVal = '';
								if (pdpVarId === "a1") {
									var colorAttrDef = thisProduct.getAttrByID('a1');
									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
										}
										
										// PJP: Changed to use the title, not innerHTML
										colorVal = jQuery(this).attr("title");
										var swatchUrl = findSwatch(colorVal); // find swatch url
										
										if (swatchUrl && swatchUrl != "") {
											jQuery(this).find("span:first-child").css("background", "url(" + swatchUrl + ")");
										}
										else {
											//jQuery(this).css("color", "transparent"); // no swatch image found
										}
									});
									
									varJqryObjs.data("data", {id: pdpVarId}).click(varEventHandler).hover(function(e){
										var colorVal = $(this).attr("title");
										thisProduct.showSelectedVarAttrVal("a1", colorVal);// changed from innerHTML										
										thisProduct.showImages(colorVal, colorAttrDef.vals);// changed from innerHTML
									}).mouseleave(function(e) {
										if (thisProduct.selectedVarAttribs["a1"]) {
											thisProduct.showImages(thisProduct.selectedVarAttribs["a1"], colorAttrDef.vals)
										}
										else {
											thisProduct.showImages("", [{val: "", images: model.images}]);
										}
										
										thisProduct.showSelectedVarAttrVal("a1", thisProduct.selectedVarAttribs["a1"] || "&nbsp;");
									});
								}
								else {								
									varJqryObjs.data("data", {id: pdpVarId}).click(varEventHandler);
								}
							}
						});
						
						if (thisProduct.selectedVarAttribs["a1"]) {
							// show swatch related images for the current value								
							thisProduct.showImages(thisProduct.selectedVarAttribs["a1"], thisProduct.getAttrByID('a1').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);
					if (model.master || model.productSet || model.bundle || (!model.inStock && model.avStatus === app.constants.AVAIL_STATUS_NOT_AVAILABLE && !model.productSet)) {
						jQuery("div.addtocart button").attr("disabled", "disabled");
						jQuery("div.addtocart").addClass("disabled");
					}
																			
					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) {
							disableAddToCart(thisProduct);
						} 
						else {
							enableAddToCart(thisProduct);
						}
					}						

					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 enableAdd2Cart = 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))) {
										enableAdd2Cart = 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 (enableAdd2Cart && (model.productSet || model.inStock)) {
									enableAddToCart(thisProduct);

									// show total price
									thisProduct.showUpdatedPrice(price);
								} else {
									disableAddToCart(thisProduct);
								}
							}
						);
					});
				},

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