var productId;
var Cart;
var previousImageURL = '';
var productSizeSelector,productColorSelector,productTrimSelector;
var viewerReset = false;
var image = new Object();

//(function($) {
	//----------------------------
	// PRODUCT DETAIL PAGE BEGIN
	//----------------------------
	var ContentExpander = function() {
		return {
			viewAll: function(klass) {
				var ul = $("."+klass);
				ul.find("li:gt(1)").slideToggle(400);
			},
			liveLoad: function() {	
				/**
				 * LOKVIK-1828 : liveLoad is called once on doc ready. Using 'liveQuery', any new elements that match
				 * these queries will have their events registered...even after AJAX loading
				 **/

				// For View All / Close Toggle
				// This is repeated in objects.js
				$(".view-all").live("click", function() {
					 $(this).parent().find("ul li.toggle").show();
					 $(this).parent().find("span.current-count").hide();
					 $(this).parent().find("span.full-count").show();
					 $(this).parent().find(".view-close").show();
					 $(this).hide();
					 return false;
					}
				);

				$(".view-close").live("click", function() {
					 $(this).parent().find("ul li.toggle").hide();
					 $(this).parent().find("span.current-count").show();
					 $(this).parent().find("span.full-count").hide();
					 $(this).parent().find(".view-all").show();
					 $(this).hide();
					 return false;
					}
				);
			}
		};
	}();
	
	var ProductConfigurator = function() {
		return {
			liveLoad: function() {
				/**
				 * LOKVIK-1828 : liveLoad is called ONLY ONCE on doc ready. Using 'liveQuery', any new elements that match
				 * these queries will have their events registered...even after AJAX loading
				 **/
				$(".product-finish-item").live("click", function() {
					ProductConfigurator.selectedFinish($(this).ident());
				});				
				$(".product-trim-option-item").live("click", function() {
					ProductConfigurator.selectedTrimOption($(this).ident());
				});				
				$(".product-knob-item").live("click", function() {
					ProductConfigurator.selectedKnob($(this).ident());
				});
				$(".product-gas-type-item").live("click", function() {																
					ProductConfigurator.selectedGasType($(this).ident());
				});
				$(".product-burner-config-item").live("click", function() {																
					ProductConfigurator.selectedBurnerConfig($(this).ident());
				});
				$(".product-door-style-item").live("click", function() {
					ProductConfigurator.selectedDoorStyle($(this).ident());
				});
				$(".product-door-hinge-item").live("click", function() {
					ProductConfigurator.selectedDoorHinge($(this).ident());
				});
				$(".product-interior-config-item").live("click", function() {
					ProductConfigurator.selectedInteriorConfig($(this).ident());
				});								
				
				$(".alternate-images .alternate-image-item").live("click", function() {
					var imageId = $(this).ident();
					viewerReset = true;
					SkuFinder.lookupImageById(imageId, function(result) {
						var altHei;
						var altWid;
						var imageURL = result[0];
						if (previousImageURL != imageURL) {
							if (imageURL != null || imageURL != '') {
								// get javascript file that contains image properties
								var alternateImage = imageURL;
								var rootDir = S7ConfigClient.isRoot;
								alternateImage = alternateImage.replace(rootDir, '');
								var js = rootDir + alternateImage + "?req=imageprops,javascript";
								
								// get new width and height and set new image in viewer
							    $.getScript(js, function() {
							    	altHei = image.height;
							    	altWid = image.width;
									alternateImage  = alternateImage + modifiers;
							    	s7zoom.setImage(rootDir + alternateImage,'true', altWid, altHei);
							    });
							    $('#scene7AltTag').text('');
								previousImageURL = imageURL;
							} else {
								// display the na image if the image is not available
								if (imageURL !=  '/VikingRange/na' + modifiers) {
									imageURL  = '/VikingRange/na' + modifiers;
									s7zoom = new SjZViewer(S7ConfigClient.isRoot,imageURL,420,485);
									loadScene7Presets();
									previousImageURL = imageURL;
								    $('#scene7AltTag').text('');
								}
								viewerReset = true;
							}
						}
					});
				});			
			},
			scan: function() {
				//jQuery 1.3 'live' does NOT implement "change"...so, improvise to keep this event from registering more than once
				if (!productSizeSelector && $(".product-size-selector").length > 0) {
					$(".product-size-selector").change(function() {
						ProductConfigurator.selectedSizeOption($.trim($(this).children(":selected").html()));
					}); productSizeSelector = true;
				}
				if (!productColorSelector && $(".product-color-selector").length > 0) {
					$(".product-color-selector").change(function() {
						ProductConfigurator.selectedColorOption($.trim($(this).children(":selected").html()));
					}); productColorSelector = true;
				}
				if (!productTrimSelector && $(".product-trim-selector").length > 0) {
					$(".product-trim-selector").change(function() {
						ProductConfigurator.selectTrimOption($.trim($(this).children(":selected").html()));
					}); productTrimSelector = true;
				}
				if ($('.product-gas-type-item').length > 0) {
					var options = {cls: 'jquery-radio-01', empty: '/consumer/images/empty.png'};
					$('.product-gas-type-item').checkbox(options).bind('check', function(){
						ProductConfigurator.selectedGasType($(this).ident());
					});
					
					if ($('.product-fuel-selector').length > 0) {
	                    $(".product-fuel-selector").change(function() {
	                    	ProductConfigurator.selectedFuelOption($.trim($(this).children(":selected").html()));
	                    });
					}
				}
			},
			selectedFinish: function(finishId) {
				$(".finishId").val(finishId);
				if ($(".product-color-selector").length > 0) {
					SkuFinder.lookupNameOfFinish(finishId, function(finishName) {
						if (finishName) {
							$(".product-color-selector").val(finishName);
							$(".colorOption").val(finishName);
						}
						ProductConfigurator.lookupSku();
					});
				} else {
					ProductConfigurator.lookupSku();
				}
			},
			selectedTrimOption: function(trimOptionId) {
				$(".trimOptionId").val(trimOptionId);
				if ($(".product-trim-selector").length > 0) {
					SkuFinder.lookupNameOfTrim(trimOptionId, function(trimName) {
						if (trimName) {
							$(".product-trim-selector").val(trimName);
							$(".trimOption").val(trimName);
						}
						ProductConfigurator.lookupSku();
					});
				} else {
					ProductConfigurator.lookupSku();
				}
				//ProductConfigurator.lookupSku();
			},			
			selectedKnob: function(knobId) {
				$(".knobId").val(knobId);
				ProductConfigurator.lookupSku();
			},
			selectedGasType: function(gasTypeId) {
				$(".gasTypeId").val(gasTypeId);
				if ($(".product-fuel-selector").length > 0) {
					var gasTypeDescription = $('#'+gasTypeId).parent().find('label').text();
					$(".product-fuel-selector").val(gasTypeDescription);
					ProductConfigurator.lookupSku();
				} else {
					ProductConfigurator.lookupSku();
				}
			},
			selectedBurnerConfig: function(burnerConfigId) {
				$(".burnerConfigId").val(burnerConfigId);
				ProductConfigurator.lookupSku();
			},
			selectedDoorStyle: function(doorStyleId) {
				$(".doorStyleId").val(doorStyleId);
				ProductConfigurator.lookupSku();
			},
			selectedDoorHinge: function(doorHingeId) {
				$(".doorHingeId").val(doorHingeId);
				ProductConfigurator.lookupSku();
			},
			selectedInteriorConfig: function(interiorConfigId) {
				$(".interiorConfigId").val(interiorConfigId);
				ProductConfigurator.lookupSku();
			},
			selectedColorOption: function(color) {
				$(".colorOption").val(color);
				color = color.replace(/\s+/g, '');
				$(".finishId").val($(".product-finish-name-"+color).ident());
				ProductConfigurator.lookupSku();
			},
			selectedSizeOption: function(size) {
				$(".sizeOption").val(size);
				ProductConfigurator.lookupSku();
			},
			selectTrimOption: function(trim) {
				trim = trim.replace(/\s+/g, '');
				$(".trimOptionId").val($(".product-trim-name-"+trim).ident());
				ProductConfigurator.lookupSku();
			},
			selectedFuelOption: function(gasTypeDescription) {
				$(".gasTypeId").val(gasTypeDescription);
				var gasTypeId = $('#'+gasTypeId).parent().find('label').text();
				$('.radio-01').each(function(index) {
					var selectData =($.trim($(this).text()));
					if(gasTypeDescription == selectData) {
						var checkInput = $(this).find('input.product-gas-type-item');
						$(checkInput).attr("checked", "checked");
					}
				});
			},
			makeDefaultSelections: function() {
				//only set to a default if the existing finishId is empty, otherwise, it has already been set
				if ($(".finish-list").length > 0 && $(".finishId").length > 0 && $(".finishId").val().length < 1) {
					var defaultFinishId = null;
					if ($(".product-color-selector").length > 0) {
						var color = $.trim($(".product-color-selector option:selected").html());
						defaultFinishId = $(".product-finish-name-" + color.replace(/\s+/g, '')).attr("id");
					} else {
						defaultFinishId = $(".finish-list").find(".product-finish-item:first").attr("id");
					}
					$(".finishId").val(defaultFinishId);
				}
				
				if ($(".burner-config-list").length > 0 && $('.burnerConfigId').val().length < 1) {
					var burnerConfigListId = $(".burner-config-list").find(".product-burner-config-item:first").attr("id");
					$(".burnerConfigId").val(burnerConfigListId);
				}
				
				if ($(".trim-option-list").length > 0 && $('.trimOptionId').val().length < 1) {
					var defaultTrimOptionId = $(".trim-option-list").find(".product-trim-option-item:first").attr("id");
					$(".trimOptionId").val(defaultTrimOptionId);
				}
				
				if ($(".door-style-list").length > 0 && $('.doorStyleId').val().length < 1) {
					var defaultDoorStyleId = $(".door-style-list").find(".product-door-style-item:first").attr("id");
					$(".doorStyleId").val(defaultDoorStyleId);
				}
				
				if ($(".door-hinge-list").length > 0 && $('.doorHingeId').val().length < 1) {
					var defaultDoorHingeId = $(".door-hinge-list").find(".product-door-hinge-item:first").attr("id");
					$(".doorHingeId").val(defaultDoorHingeId);
				}
				
				if ($(".interior-config-list").length > 0 && $('.interiorConfigId').val().length < 1) {
					var defaultInteriorConfigId = $(".interior-config-list").find(".product-interior-config-item:first").attr("id");
					$(".interiorConfigId").val(defaultInteriorConfigId);
				}
				
				if ($(".product-size-selector").length > 0 && $('.sizeOption').val().length < 1) {
					var defaultSize = $.trim($(".product-size-selector").find(":selected").html());
					$(".sizeOption").val(defaultSize);
				}
				
				if ($(".product-color-selector").length > 0 && $('.colorOption').val().length < 1) {
					var defaultColor = $.trim($(".product-color-selector").find(":selected").html());
					$(".colorOption").val(defaultColor);
				}
			
				//if ($(".knob-list").length > 0) {
				//	var defaultKnobId = $(".knob-list").find(".product-knob-item:first").attr("id");
				//	$(".knobId").val(defaultKnobId);
				//}
				
				//if ($(".finishId").val() || $(".trimOptionId").val() || $(".knobId").val() 
				//		|| $(".burnerConfigId").val() || $(".doorStyleId").val() 
				//		|| $(".doorHingeId").val() || $(".interiorConfigId").val()) {
				//	ProductConfigurator.lookupSku();
				//}
				
				
				if ($(".product-gas-type-item").length > 0 && $('.gasTypeId').val().length < 1) {
					var defaultGasTypeId = $(".gas-type-list").find(".product-gas-type-item:first").attr("id");
					$(".gasTypeId").val(defaultGasTypeId);
				}
				
			},
			lookupSku: function(callback) {
				var finishId = $(".finishId").val();
				var trimOptionId = $(".trimOptionId").val();
				var knobId = $(".knobId").val();
				var gasTypeId = $(".gasTypeId").val();
				var burnerConfigId = $(".burnerConfigId").val();
				var doorStyleId = $(".doorStyleId").val();
				var doorHingeId = $(".doorHingeId").val();
				var interiorConfigId = $(".interiorConfigId").val();
				var colorOption = $(".colorOption").val();
				var sizeOption = $(".sizeOption").val();
				SkuFinder.lookupImageForSku(productId, finishId, trimOptionId, knobId, gasTypeId, burnerConfigId, doorStyleId, doorHingeId, interiorConfigId, sizeOption, colorOption, function(result) {
                    try {
                        ProductConfigurator.callExternalImage(result[0], result[1]);
                    } catch(e) {
                        if (e.name == "TypeError") {
                            // Try the request again.
                            setTimeout(function() {
                                ProductConfigurator.callExternalImage(result[0], result[1]);
                            }, 200);
                        }
                    }
                    
                    if (result[3]) {
                    	$('input.currentSkuId').val(result[3]);
                    }
                    
					var node = null;
					if ($(".product-size-selector").length > 0) {
						node = $(".product-size-selector").closest("form");
					} else if ($(".product-color-selector").length > 0) {
						node = $(".product-color-selector").closest("form");
					} else if ($(".product-trim-selector").length > 0) {
						node = $(".product-trim-selector").closest("form");
					}
					PriceChanger.changePrice(productId, result[2], result[3], node);
					
					if (result[4]) {
						$(".product-size-selector").find("option:selected").removeAttr("selected");
						$(".product-size-selector").find("option:[value="+result[4]+"]").attr("selected", "selected");
					}
					
					if (result[5]) {
						$("#sku-name-div").html(result[5]);
					}
					
					if (callback != undefined) {
						callback();
					}
				});
			},
			callExternalImage: function(imageURL, imageAltText) {
				var rootDir = S7ConfigClient.isRoot;
				var altHei;
				var altWid;
				if (imageURL != previousImageURL) {
					if (imageURL == null || imageURL == '') {
						rootDir = S7ConfigClient.isRoot;
						previousImageURL = imageURL;
						imageURL  = '/VikingRange/na';
						var js = rootDir + imageURL + "?req=imageprops,javascript";
					    $.getScript(js, function() {
					    	altHei = image.height;
					    	altWid = image.width;
					    	imageURL  = imageURL + modifiers;
					    	s7zoom.setImage(rootDir + imageURL,'true', altWid, altHei);
					    });
						s7zoom.setMaxZoom(zoomlimit); 
						s7zoom.setZoomStep(zoomsteps); 
					    $('#scene7AltTag').text('');
						viewerReset = true;
					} else if (viewerReset != true && imageURL != null) {
						rootDir = rootDir + company + '/'
						previousImageURL = imageURL;
						imageURL = imageURL.replace(rootDir, '');
					    $('#scene7AltTag').text(imageAltText);
						changeImage(imageURL);
					} else {
						rootDir = S7ConfigClient.isRoot;
						previousImageURL = imageURL;
						imageURL = imageURL.replace(rootDir, '');
						var js = rootDir + imageURL + "?req=imageprops,javascript";
					    $.getScript(js, function() {
					    	altHei = image.height;
					    	altWid = image.width;
					    	imageURL  = imageURL + modifiers;
					    	s7zoom.setImage(rootDir + imageURL,'true', altWid, altHei);
					    });
					    $('#scene7AltTag').text(imageAltText);
						viewerReset = false;
					}
				}
			}
		};
	}();
	//----------------------------
	// PRODUCT DETAIL PAGE END
	//----------------------------


	//----------------------------
	// SUBCATEGORY PAGE BEGIN
	//----------------------------
	var SubCategoryImageNav = function() {
		return {
			liveLoad: function() {	
				//$(".child-category-image").click(function(i) {
				$(".child-category-image").live("click", function(i) {
					//alert($("#child-cat-anchor-"+$(this).ident()).attr("class"));
					$("#child-cat-anchor-"+$(this).ident()).click();
					return false;
				});
			}
		}
	}();
	//----------------------------
	// SUBCATEGORY PAGE BEGIN
	//----------------------------
	

	//----------------------------
	// CATEGORY PAGE BEGIN
	//----------------------------
	var QuaternaryNav = function() {
		var loadedQuaternaryTabs = {};
		return {
			quaternaryTabClick: function() {
				$('.quaternary-tabbed-content-item').hide();
				var repoId = $(this).attr("id");
				var quat = null;
				
				if (loadedQuaternaryTabs[repoId]) {
					quat = $(['#quaternary-content-', repoId].pack());
					quat.show();
				} else {
					$.get("/consumer/products/tabs/category_quaternary_nav_tab.jsp", {categoryId: repoId}, function(data) {
				    	data = Ajax.parse(data);
						quat = $("#quaternary-content-"+repoId);
						quat.html(data).show();
						loadedQuaternaryTabs[repoId] = repoId;
						Pane.buy_online(quat);
				    });
				}
				TabToggler.toggle("category-find-featured-products-"+repoId, false);
				return false;
			},
			load: function(selectedQuaternaryTab) {
				$(".quaternary-nav-tab").unbind("click", QuaternaryNav.quaternaryTabClick).bind("click", QuaternaryNav.quaternaryTabClick);
				if (selectedQuaternaryTab) {
					if (loadedQuaternaryTabs[selectedQuaternaryTab]) {
						$(['#quaternary-content-', selectedQuaternaryTab].pack()).show();
					} else {
						if(typeof ClickTaleExec=='function') {
							ClickTaleExec("$('#'+selectedQuaternaryTab).click()");
						}
						$("#"+selectedQuaternaryTab).click();
					}
				} else {
					if(typeof ClickTaleExec=='function') {
						ClickTaleExec("$('.quaternary-nav-tab:first').click()");
					}
					$(".quaternary-nav-tab:first").click();
				}
			}
		};
	}();

    var ExclusiveFinish = function() {
        var TooltipLayer = function(o) {
            var node = o;
            var layerId = 'swatch-tooltip';
            $(['#', layerId].pack()).remove();
            var tip = $('<div id="swatch-tooltip"><div id="swatch-tooltip-content"></div><div id="swatch-tooltip-bottom">&nbsp;</div></div>').hide();
            $('body').append(tip);
            return {
                show: function(text) {
                    // Non-IE browsers get to see the tooltip all on one line.
                    if (!$.browser.msie) {
                        tip.css({
                            width: 'auto'
                        });
                    }
                    tip.find('div:first').text(text);
                    var offset, top, left, w, h;
                    offset = node.offset();
                    top = offset.top;
                    left = offset.left;
                    setTimeout(function() {
                        tip.show();
                        tip.css({
                            top: top - tip.height() + 6,
                            left: (left + node.width() / 2) - (tip.outerWidth() / 2)
                        });
                        tip.css('z-index', 2001);
                        if ($.browser.msie && $.browser.version < 7) {
                           tip.find('div:last').remove();
                           tip.css({
                               top: node.offset().top - tip.height()
                           });
                        }
                    }, 250);

                },
                destroy: function() {
                    tip.remove();
                }
            };
        };
        return {
            mouseovers: function(parentNav, items) {
                var layer = null;
                var defaultItems = '.featured-product-finish-item, .product-finish-item, .product-trim-option-item, .product-burner-config-item, .product-door-hinge-item, .product-door-style-item, .product-interior-config-item';
                var targetItems = $(defaultItems);
                
                if (items && items.length > 0) {
                	targetItems = items;
                } else if (parentNav && parentNav.length > 0) {
                	targetItems = parentNav.find(defaultItems);
                }
                targetItems.bind('mouseenter', function() {
                    var text = $(this).find('span').text();
                    layer = new TooltipLayer($(this));
                    layer.show(text);
                    return false;
                }).bind('mouseleave', function() {
                    if (layer) {
                    	layer.destroy();
                    }
                });
            }
        };
    }();

	var FeaturedProduct = function() {
		var scene7Params = "?fmt=png-alpha&wid=220&hei=210&resmode=sharp2&op_usm=1,1,10,0";
		return {
			liveLoad: function() {	
				$(".featured-product-finish-item").live("click", function() {
					var featuredProductId = $(this).parents("ul:first").ident();
					FeaturedProduct.selectedFinish(featuredProductId, $(this).ident());
				});
			},
			selectedFinish: function(featuredProductId, finishId) {
				// only do lookup and reload image if a different finish option was clicked on
				if ($("#finish"+featuredProductId).val() != finishId) {
					$("#finish"+featuredProductId).val(finishId);
					FeaturedProduct.lookupSku(featuredProductId);
				}
			},
			lookupSku: function(featuredProductId) {
				var finishId = $("#finish"+featuredProductId).val();
				var knobId = $("#knob"+featuredProductId).val();
				var trimOptionId = $("#trimOption"+featuredProductId).val();
				var gasTypeId = $(".gasTypeId").val();
				var burnerConfigId = $("#burnerConfig"+featuredProductId).val();
				var doorStyleId = $("#doorStyle"+featuredProductId).val();
				var doorHingeId = $("#doorHinge"+featuredProductId).val();
				var interiorConfigId = $("#interiorConfig"+featuredProductId).val();
				SkuFinder.lookupImageForSku(featuredProductId, finishId, trimOptionId, knobId, gasTypeId, burnerConfigId, doorStyleId, doorHingeId, interiorConfigId, '', '', function(imageProps) {
					FeaturedProduct.loadFeaturedProductImage(featuredProductId, imageProps[0]);
				});
			},
			loadFeaturedProductImage: function(featuredProductId, imageURL) {
                var img = new Image();
                img.src = imageURL+scene7Params;

                var featuredProductImage = $("#image"+featuredProductId);
                featuredProductImage.attr("src", imageURL+scene7Params);
				$(featuredProductImage).removeClass("dimensions-non-scene7");
                PNG.fix();
			}
		};
	}();
	//----------------------------
	// CATEGORY PAGE END
	//----------------------------


	var PriceChanger = function() {
		return {
			changePrice: function(productId, sellable, skuId, flyout) {
				if (sellable == "true" && skuId) {
					$.get("/consumer/products/product_price_fragment.jsp", {id: productId, skuId: skuId}, function(stringFromServer) {
                        // If there is a flyout on the page somewhere its price also needs to be updated.
                        if (flyout) {
                            flyout.find('li.price,.priceupdate').html(stringFromServer);
                        }
					});
				}
			}
		};
	}();

	var TabToggler = function() {
		return {
			toggle: function(hash, defaultTab) {
                hash = hash.replace(/-tab$/, '');
                tab = hash;
                new Layer().remove();
				$('#tab-list li').removeClass('active');
				$('#tab-list-2 li').removeClass('active');
				$(".quaternary-nav-tab").removeClass("active");
				if (hash.indexOf("category-find-featured-products") == 0) {
					tab = "category-find-featured-products";
					quaternaryTab = hash.substr(32);
					if (quaternaryTab) {
						$("#"+quaternaryTab).addClass("active");
					}
				}
                $(['#', tab, '-tab'].pack()).addClass('active');
                if (!defaultTab) {
					window.location.hash = hash;
				}

				/*
					Some pages require a vertical divider between two columns within the page. This can only
					be done by using a background image. This will toggle the appropriate background image.
				*/
				if (hash == "product-accs") {
					Nav04BackgroundToggler("nav04-divider-product-accs");
				} else {
					Nav04BackgroundToggler("nav04-divider");
				}
				return false;
			}
		};
	}();
	
	Cart = function() {
		return {
			add: function(form) {
				var action = form.attr('action');
				try { 
					var data = {};
					// Add x/y hidden inputs for input type=image or else ATG won't accept the form
					form.find('input:image, input:submit').each(function(i) {

						var name = $(this).attr('name');
						var x = [name, '.x'].pack();
						var y = [name, '.y'].pack();
						$.each([x, y], function(k, v) {
							var input = $(['<input type="hidden" name="', v, '" value="1" />'].pack());
							form.append(input)
						});
					});

					form.find('input, textarea').each(function(i) {
						var k = $(this).attr('name');
						var v = $(this).attr('value');
						if (k) {
							data[k] = v;
						}

					});

					form.find('select').each(function(i) {
						var k = $(this).attr('name');
						var v = $(this).find('option:selected').val();
						if (k) {
							data[k] = v;
						}
					});


					var post = function(response) {
						var id = $('#product-id').val();
						$.get('/consumer/popups/flyouts/cart/recently_added.jsp', {id: id}, get);
					};

					// This will run after the data has been posted to the server.
					var get = function(response) {
						// Scroll to the top of the page
						$.scrollTo('body:eq(0)', 500, { easing: 'linear'});
						// Make the cart icon turn blue.
						$('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-blue.gif)')
						// Hide all other popups.
						$('#nav-utility-wrapper').find('.popped').fadeOut('fast');

						// Build the popup and position it correctly.
						var popup = $(response);

                        $('#cart_dropdown_wrapper').append(popup);
                        var updatedQuantity = $.trim(popup.find('#cart-quantity-update').text());

						popup.css('top', $('#cart_dropdown_wrapper').height().pixelate());

						// Show the popup and update the quantity displayed on the page.
						popup.fadeIn('fast', function() {
							$(this).addClass('popped');
							$(this).find('.closer').click(function() {
								popup.fadeOut('fast');
							});
							IEOnly.zIndex($(this), 2000000);
							$('#current-cart-quantity').text(updatedQuantity);
							$('#global_cart_popup').empty().append(popup.children().clone(true));
                            setTimeout(function() {
                                popup.find('#cart-flyout-other-items').slideDown("fast");
                                setTimeout(function() {
                                    popup.find('#cart-actions').slideDown();
                                }, 500);
                            }, 500);
						});


						// Remove the popup
						var timeout = setTimeout(function() {
							popup.fadeOut('slow', function() {
								$('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-gray.gif)')
								popup.remove();
							});
						}, 20000);

						// Halt the scheduled removal of the popup and remove it when the mouse leaves.
						popup.bind('mouseenter', function() {
							clearTimeout(timeout);
							$(this).bind('mouseleave', function() {             
								return;
								$(this).fadeOut('fast', function() {
									$('#global_cart_opener').css('background-image', 'url(/consumer/images/header/cart-gray.gif)');
									popup.remove();
								});
							});
						});
					};

					// Submit the form in the background.
					$.post(action, data, post);
				} catch (e) {
					Log.error(e);
				}
				// Do not let the form submit on its own.
				return false;
			}
		};
	}();

	var Pane = function() { 
		return {
			// Find all the "buy-online" links and attach clicks to them
			// also finds any add to cart forms on the page
			buy_online: function(pane) {
                pane.find('.add-to-cart :submit').click(function() {
                    var form = $(this).parent('form:first');
                    try {
                        Cart.add($(form));
                        new Layer().fadeOut();
                        return false;
                    } catch(ex) {
                        alert(ex);
                    }
                    return false;
                });
				pane.find('a.buy-online').click(function(e) {
					var link = $(this);
					var id = $(this).ident().split(':')[1];
					AddToCartFormPicker.chooseAddToCartForm(id, function(form) {
						var url = '/consumer/products/ajax/add_to_cart.jsp';
						if (form == 'size') {
							url = '/consumer/products/ajax/add_to_cart_size.jsp';
						} else if (form == 'color') {
							url = '/consumer/products/ajax/add_to_cart_color.jsp';
						} else if (form == 'sizeColor') {
							url = '/consumer/products/ajax/add_to_cart_size_color.jsp';
						} else if (form == 'gasType') {
							url = '/consumer/products/ajax/add_to_cart_gas_type.jsp';
						} else if (form == 'trim') {
							url = '/consumer/products/ajax/add_to_cart_trim.jsp';
						}
						
						$.get(url, {id: id}, function(data) {
							var html = $(data);
							var layer = new Layer(link);
	                        layer.addClass('buy-online-flyout')
	                        layer.addContent(html);
	                        layer.addCloseButton();
	                        layer.moveUpHalfway();
	                        // these scene 7 parameters come from /consumer/products/ajax/add_to_cart*.jsp files
	                        // make sure they match
	                        var buyOnlinePopupScene7Params = "?fmt=jpeg&wid=170&hei=130&resmode=sharp2&op_usm=1,1,10,0";
	                        
	                        $(".product-size-selector").change(function() {
	                        	var size = $.trim($(".product-size-selector").children(":selected").html());
	                        	var color = $.trim($(".product-color-selector").children(":selected").html());
	                        	SkuFinder.lookupImageForSku(id, '', '', '', '', '', '', '', '', size, color, function(result) {
                                    
                        			PriceChanger.changePrice(id, result[2], result[3], layer.getNode());
                        			
                        			if (result[0]) {
                        				$(".buy-online-popup-image").attr("src", result[0]+buyOnlinePopupScene7Params);
                        				$(".buy-online-popup-image").attr("alt", result[1]);
                        			}
                        			
                        			if (result[3]) {
                        				$(".buy-online-link").each(function() {
                        					var qsp = new QueryStringParser();
                        					$(this).attr("href", qsp.set($(this).attr("href"), "skuId", result[3]));
                        				});
                        			}
                        			
                        			if (result[4]) {
                						$(".product-size-selector").find("option:selected").removeAttr("selected");
                						$(".product-size-selector").find("option:[value="+result[4]+"]").attr("selected", "selected");
                					}
	                        	});
	                        });
	                        $(".product-color-selector").change(function() {
	                        	var size = $.trim($(".product-size-selector").children(":selected").html());
	                        	var color = $.trim($(".product-color-selector").children(":selected").html());
	                        	SkuFinder.lookupImageForSku(id, '', '', '', '', '', '', '', '', size, color, function(result) {
                        			PriceChanger.changePrice(id, result[2], result[3], layer.getNode());
                        			
                        			if (result[0]) {
                        				$(".buy-online-popup-image").attr("src", result[0]+buyOnlinePopupScene7Params);
                        				$(".buy-online-popup-image").attr("alt", result[1]);
                        			}
                        			
                        			if (result[3]) {
                        				$(".buy-online-link").each(function() {
                        					var qsp = new QueryStringParser();
                        					$(this).attr("href", qsp.set($(this).attr("href"), "skuId", result[3]));
                        				});
                        			}
                        			
                        			if (result[4]) {
                						$(".product-size-selector").find("option:selected").removeAttr("selected");
                						$(".product-size-selector").find("option:[value="+result[4]+"]").attr("selected", "selected");
                					}
	                        	});
	                        });
	                        $(".product-fuel-selector").change(function() {
	                        	var fuel = $.trim($(this).children(":selected").attr("id"));
	                        	SkuFinder.lookupImageForSku(id, '', '', '', fuel, '', '', '', '', '', '', function(result) {
                        			PriceChanger.changePrice(id, result[2], result[3], layer.getNode());
                        			if (result[0]) {
                        				$(".buy-online-popup-image").attr("src", result[0]+buyOnlinePopupScene7Params);
                        				$(".buy-online-popup-image").attr("alt", result[1]);
                        			}
                        			
                        			if (result[3]) {
                        				$(".buy-online-link").each(function() {
                        					var qsp = new QueryStringParser();
                        					$(this).attr("href", qsp.set($(this).attr("href"), "skuId", result[3]));
                        				});
                        			}
                        			
                        			if (result[4]) {
                						$(".product-trim-selector").find("option:selected").removeAttr("selected");
                						$(".product-trim-selector").find("option:[value="+result[4]+"]").attr("selected", "selected");
                					}
	                        	});
	                        });
	                        $(".product-trim-selector").change(function() {
	                        	var trimOption = $.trim($(this).children(":selected").attr("id"));
	                        	SkuFinder.lookupImageForSku(id, '', trimOption, '', '', '', '', '', '', '', '', function(result) {
                        			PriceChanger.changePrice(id, result[2], result[3], layer.getNode());
                        			if (result[0]) {
                        				$(".buy-online-popup-image").attr("src", result[0]+buyOnlinePopupScene7Params);
                        				$(".buy-online-popup-image").attr("alt", result[1]);
                        			}
                        			
                        			if (result[3]) {
                        				$(".buy-online-link").each(function() {
                        					var qsp = new QueryStringParser();
                        					$(this).attr("href", qsp.set($(this).attr("href"), "skuId", result[3]));
                        				});
                        			}
                        			
                        			if (result[4]) {
                						$(".product-trim-selector").find("option:selected").removeAttr("selected");
                						$(".product-trim-selector").find("option:[value="+result[4]+"]").attr("selected", "selected");
                					}
	                        	});
	                        });
	
							$('#ajax-add-to-cart button').click(function() {
								var form = $(this).parent('form:first');
								try {
									form.submit(function() {
										Cart.add($(this));
										new Layer().fadeOut();
										return false;
									}).submit();
								} catch(ex) {
									alert(ex);
								}
								return false;
							});
						});
					});

					
					return false;
				});

			}
		};
	}();

	var activateTab = function(activeTab,loadedTabs) {
		var tab = activeTab.attr('href').split('#')[1];
		var catId = null;
		var file = null;
		var quaternaryTab = null;
		overviewTabActivated = false;
		
		if(tab.indexOf("subcategory-child-cat") == 0)
		{
			catId = tab.split('-')[3];
			file = tab.substring(0,21).replace(/-/g, '_');
		}
		else if (tab.indexOf("category-find-featured-products") == 0)
		{
			quaternaryTab = tab.replace(/-tab$/,'').substr(32);
			tab = "category-find-featured-products";
			file = tab.replace(/-/g, '_');
		}
		else
		{
			file = tab.replace(/-/g, '_');
		}
		$('#tabbed-content .tabbed-content-item').hide();

		if (loadedTabs[tab]) {
			$(['#', tab, '-tab-content'].pack()).show();
			if (file == 'product_overview') {
				//this allows a Firefox flash reload when 'callInitialExternalImage' is called
				overviewTabActivated = true;
				if (!$.browser.msie) {
					$("#sku-name-div").html("");
				}
    		}
            /*LOKVIK2084(); ... replaced with mozillaFlashFix using the overviewTabActivated bool*/
		} else {
			var url = ['/consumer/products/tabs/', file, '_tab.jsp'].join('');
            var pane = $(['#', tab, '-tab-content'].pack());
            pane.show();
            
            var params = {id: productId, subcat: catId};
            var urlQsp = new QueryStringParser();
    		var quoteItemIdVal = urlQsp.get('quoteItemId');
    		var expandOptionVal = urlQsp.get('expand');
    		if (quoteItemIdVal && quoteItemIdVal.length > 0) {
    			params.quoteItemId = quoteItemIdVal;
    		}
    		if (expandOptionVal && expandOptionVal.length > 0) {
    			params.expand = expandOptionVal;
    		}
            
			$.get(url, params, function(data) {
                pane.removeClass("loading");
                pane.html(data).show();
				Pane.buy_online(pane);
				loadedTabs[tab] = tab;
				ExclusiveLinks.scan();
	            ProductFinder.find({openRight: false});
	        	FilteredSearch.search();
	        	//ContentExpander.scan();
	        	ProductConfigurator.scan();
	        	if ($('.make-default-selection').length > 0 && $('.make-default-selection').val() == 'true') {
	    			ProductConfigurator.makeDefaultSelections();
	        	}
	        	//FeaturedProduct.scan();
	        	QuaternaryNav.load(quaternaryTab);
                Paginator.paginate($('#filtered-product-list'));
                Paginator.scroll($('#filtered-search-results'));
                FilteredSearchFormatter.add_sliders();
                ExclusiveFinish.mouseovers();
                //SubCategoryImageNav.scan();
                ModifyHtmlText('div.specifications-and-documentation a', 'C4 Cookbook', 'Cookbook');
                /*LOKVIK2084(); ... replaced with mozillaFlashFix using the overviewTabActivated bool*/                
			});
		}
		TabToggler.toggle(tab, false);
		return false;
	};

    var LOKVIK2084 = function() {
        if ($.browser.mozilla) {
            var cookie = new Cookie();
            var qsp = new QueryStringParser();
            var productId = qsp.get("id"); // This is the id of the product on the current page
            var cookieValue = cookie.get("lastSwatchId"); // This looks like "productId-123456" where 123456 is the numeric id (argh) of the last-clicked color option.
            if (cookieValue) {
                // Check to see if the product id stored in the cookie is the same as the id param in the url.
                var chunks = cookieValue.split("-");
                var storedProductId = chunks[0];
                var storedSwatchId = chunks[1];
                if (storedProductId) {
                    if (productId !== storedProductId) {
                        cookie.expire("lastSwatchId");
                        return false;
                    }
                }
                var li = $(['#', storedSwatchId].pack());
                if (li.length > 0) {
                    ProductConfigurator.selectedFinish(li.ident());
                }
            }
            $('ul.swatch li').click(function() {
                var id = [productId, $(this).ident()].join('-');
                cookie.set("lastSwatchId", id);
            });
        }
    };

	var TabLoader = function() {

		var qsp = new QueryStringParser();
		productId = qsp.get('id');
		if (!productId) {
			return false;
		}
        if ($('#tab-list').length < 1) {
            return false;
        }

        // Add "loading" images to each .tabbed-content-item
        // It needs a special-looking name because IE6 can't parse multiple class names in CSS
        $('.tabbed-content-item').addClass('loading');


        // Initial page load:

		var loadedTabs = {}; // Stores the tabbed content items that have already been loaded for faster retrieval later

		// Find the id of the tab to show in the window location's hash. For example, if the current URL
		// is http://www.site.com/place.jsp?id=1234#more-info, then div#more-info should be loaded and shown.
		var hash = window.location.hash;
		var tab = null;
		var quaternaryTab = null;
		var url = null;
		var file = null;
		var catId = null; //for use with the subategory pages to handle further categories (i.e. classic & custom)
        var defaultTab = $('#tab-list').find('.default-tab:first').ident();
        var useDefaultTab = false;
		//var defaultTab = "overview"; // The tabbed content item to show if there is no hash present
		if (hash) {
			tab = hash.split('#')[1];
		} else {
			useDefaultTab = true;
			tab = defaultTab;
		}
		
		if(tab.indexOf("subcategory-child-cat") == 0)
		{
			catId = tab.split('-')[3];
			file = tab.substring(0,21).replace(/-tab$/, '').replace(/-/g, '_');   // Files on the server are separated with underscores, while selector names are separated with hyphens
		}
		else if (tab.indexOf("category-find-featured-products") == 0)
		{
			quaternaryTab = tab.replace(/-tab$/,'').substr(32);
			tab = "category-find-featured-products";
			file = tab.replace(/-/g, '_');
		}
		else
		{		
        	file = tab.replace(/-tab$/, '').replace(/-/g, '_');   // Files on the server are separated with underscores, while selector names are separated with hyphens
		}

		$('#tabbed-content .tabbed-content-item').hide();
		$('#product-detail #tabbed-content #product-overview-tab-content').show();
		
		url = ['/consumer/products/tabs/', file, '_tab.jsp'].join('');
        tab = tab.replace(/-tab$/, '');
		var pane = $(['#', tab, '-tab-content'].pack());
		//see if there is an existing skuId in the current url that can help narrow this get request
		var urlQsp = new QueryStringParser();
		var skuIdVal = urlQsp.get('skuId');
		var quoteItemIdVal = urlQsp.get('quoteItemId');
 		var expandOptionVal = urlQsp.get('expand');
 		
		var params = {id: productId, subcat: catId};
 		
 		if (skuIdVal && skuIdVal.length > 0) {
 			params.skuId = skuIdVal;
 		}
		if (quoteItemIdVal && quoteItemIdVal.length > 0) {
			params.quoteItemId = quoteItemIdVal;
		}
		if (expandOptionVal && expandOptionVal.length > 0) {
			params.expand = expandOptionVal;
		}
		$.get(url, params, function(data) {
            data = Ajax.parse(data);
            if (tab != 'product-overview') {
        		$('#product-detail #tabbed-content #product-overview-tab-content').hide();
            }
			// Hide all tabbed content items and load the requested one
            pane.removeClass("loading");
			pane.html(data).show();
			loadedTabs[tab] = tab;
			Pane.buy_online(pane);
		    // Update the visuals to indicate the current tab
			TabToggler.toggle(tab, useDefaultTab);
			ExclusiveLinks.scan();
            ProductFinder.find({openRight: false});
        	FilteredSearch.search();
            //ContentExpander.scan();
        	ProductConfigurator.scan();
        	if ($('.make-default-selection').length > 0 && $('.make-default-selection').val() == 'true') {
    			if(typeof ClickTaleExec=='function') {
    				ClickTaleExec("ProductConfigurator.makeDefaultSelections()");
    			}
        		ProductConfigurator.makeDefaultSelections();
        	}
        	//FeaturedProduct.scan();
			if(typeof ClickTaleExec=='function') {
				ClickTaleExec("QuaternaryNav.load(quaternaryTab)");
			}
        	QuaternaryNav.load(quaternaryTab);
            Paginator.paginate($('#filtered-product-list'));
            Paginator.scroll($('#filtered-search-results'));
            FilteredSearchFormatter.add_sliders();
            PNG.fix();
            ExclusiveFinish.mouseovers();
            //SubCategoryImageNav.scan();
            ModifyHtmlText('div.specifications-and-documentation a', 'C4 Cookbook', 'Cookbook');
            /*LOKVIK2084(); ... replaced with mozillaFlashFix using the overviewTabActivated bool*/
            var activateRaqCheck = function() {
            	if (quoteItemIdVal && quoteItemIdVal.length > 0 && $('.request-a-quote-link').length > 0) {
            		$('.request-a-quote-link').click();
                }
            };
            /*if ($('.make-default-selection').length > 0 && $('.make-default-selection').val() == 'true') {
            	ProductConfigurator.lookupSku(activateRaqCheck);
            } else {
            	activateRaqCheck();
            }*/
			if(typeof ClickTaleExec=='function') {
				ClickTaleExec("activateRaqCheck()");
			}
            activateRaqCheck();
		});
		
		$('#tab-list a').click(function() {
			if(typeof ClickTaleExec=='function') {
				ClickTaleExec("activateTab($(this),loadedTabs)");
			}
			activateTab($(this),loadedTabs);
		});
		
		$('#tab-list-2 a').click(function() {
			if(typeof ClickTaleExec=='function') {
				ClickTaleExec("activateTab($(this),loadedTabs)");
			}
			activateTab($(this),loadedTabs);
		});
		
	};

    var Movie = function() {
        var locked = false;
        $('#media-previous, #media-next').click(function() {
            if (!locked) {
                locked = true;
            }
            var a = $(this);
            var effect = 'slide';
            var duration = 400;
            var li = $('#media-current-item');
            if (a.ident().match(/next$/)) {
                var next = li.next();
                if (next.length == 0) {
                    next = li.siblings(':first');
                }
                if (next && next.length > 0) {
                    li.hide(effect, {direction: 'left'}, duration, function() {
                        $(this).removeAttr('id');
                        next.attr('id', 'media-current-item').show(effect, {direction: 'right'}, duration, PNG.fix);
                    });
                } 
            } else {
                var prev = li.prev();
                if (prev.length == 0) {
                    prev = li.siblings(':last');
                }
                if (prev && prev.length > 0) {
                    li.hide(effect, {direction: 'right'}, duration, function() {
                        $(this).removeAttr('id');
                        prev.attr('id', 'media-current-item').show(effect, {direction: 'left'}, duration, PNG.fix);
                    });
                }
            }
            return false;
        });

        if ($.browser.msie && $.browser.version < 7) {
            $('#media-previous img, #media-next img').each(function() {
                $(this).attr('src', $(this).attr('src').replace(/png$/, 'gif'));
            });
        }
    };

    //LOKVIK-1908
    function ModifyHtmlText(query, textToFind, modifiedText) {
      if ($(query).length > 0) {
        $(query).each(function(){
          if ($(this).text() == textToFind){
            $(this).text(modifiedText);
          }    		
        });
      }    	
    }
    /*var viewContainerParent = null;
    var flashObj = null;
    function fixMozillaFlash(productOverviewWasVisible, productOvervieNowHidden) {
		if (productOverviewWasVisible && productOvervieNowHidden) {
			//if the product overview went from visible to hidden, then remove the flash object
			if ($("object#viewer-container").length > 0) { 
				viewContainerParent = $("object#viewer-container").parent();
				flashObj = $("object#viewer-container").remove();
			}
		} else if (!productOverviewWasVisible && !productOvervieNowHidden) {
			//if the product overview went from hidden to visible, then add the flash object back
			$(flashObj).prependTo($(viewContainerParent));
		}
    }*/

    var SideMenu = function() {
        return {
            // Make the <td> surrounding the links in the sidebar look clickable and
            // make it be clickable.
            allowClickingAnywhere: function() {
                $('#content-secondary .nav-secondary-products td').css({cursor: 'pointer'}).click(function() {
                    window.location = $(this).find('a:first').attr('href');
                }).hover(function() {
                    $(this).find('a:first').addClass('hover');
                }, function() {
                    $(this).find('a:first').removeClass('hover');
                });
            }
        };
    }();

    /**
     * called from callInitialExternalImage when the overview tab is activated
     * @return
     */
    var mozillaFlashFix = function() {
		if ($.browser.mozilla) {
        	ProductConfigurator.lookupSku();
	    }
	};
    
	$(document).ready(function() {
		var functions = [
			TabLoader,
            Movie,
            SideMenu.allowClickingAnywhere,
            ProductConfigurator.liveLoad,
            ContentExpander.liveLoad,
            SubCategoryImageNav.liveLoad,
            FeaturedProduct.liveLoad
		];
		$.each(functions, function(i) {
			this();
		});
		ModifyHtmlText('div.specifications-and-documentation a', 'C4 Cookbook', 'Cookbook');
	});


    /**
     * called from product page to get scene7 dhtml presets
     * 
     */
	var zoomsteps=2;
	var zoomlimit=100;
    var loadScene7Presets = function() {
		s7zoom.setBackground("0xffffff");
		s7zoom.setFadeTime(.3);
		s7zoom.setMaxZoom(zoomlimit); 
		s7zoom.setZoomStep(zoomsteps); 
		s7zoom.setFormat("jpeg");
		if (S7ConfigClient.isVersion == "2.7")
			s7zoom.setCachingModel("");
		s7zoom.addInformation("To Zoom click on the image.\\nTo Pan, click and hold the mouse while dragging.");
		s7zoom.addToPage();
		var s7navigator = new SjZoomNav(null,null,null,'relative');
		s7navigator.setViewer(s7zoom.zviewer);
		s7zoom.zviewer.setWaitIconURL("../images/scene7-viewer/text_loader.png");
		s7zoom.zviewer.setWaitIconTimer(.5,.1);
	};
	
//})(jQuery);
