// Set jQuery to not interfere with the BC prototype (or other) JS libraries.
$j = jQuery.noConflict();


// Dummy function to fix problems with BC lightbox
function initLightbox() { return true; }




// Business Catalyst Function Overrides and Formatting Extensions
jQuery(function($) {

	var WellBuilt = {
		overrides : {
			addToCart : function() {
				if ($('.shoppingCart').length === 0 || typeof AddToCart !== 'function') { return; }      
				
				var fnc = AddToCart;        
				var _alert = window.alert;
				AddToCart = function(){
					
					window.alert = function(msg){
						var p = $('<p class="productRow-addToCart-success">'+msg+'</p>');
						$('.shoppingCart').after(p);
						
						window.setTimeout(function(){
							p.fadeOut('slow', function(){
								p.remove();
							});
						}, 3000);
					};
					
					fnc.apply(this,arguments);
					
					window.alert = _alert;
					
					WellBuilt.formatting.determineTemplate();
					
				};
			},
			updateItemQuantity : function() {
				if (typeof UpdateItemQuantity !== 'function') { return; }  
				
				var fnc = UpdateItemQuantity;
				UpdateItemQuantity = function() {
					
					fnc.apply(this,arguments);
					
					WellBuilt.formatting.determineTemplate();
					window.location.reload()
				}
			},
			setShippingCountry : function() {
				if (typeof SetShippingCountry !== 'function') { return; }  
				
				var fnc = SetShippingCountry;
				SetShippingCountry = function() {
					
					fnc.apply(this,arguments);
					
					WellBuilt.formatting.determineTemplate();
				}
			},
			applyDiscountCode : function() {
				if (typeof ApplyDiscountCode !== 'function') { return; }  
				
				var fnc = ApplyDiscountCode;
				ApplyDiscountCode = function() {
					
					fnc.apply(this,arguments);
					
					WellBuilt.formatting.determineTemplate();
				}
			},
			applyGiftVoucher : function() {
				if (typeof ApplyGiftVoucher !== 'function') { return; }  
				
				var fnc = ApplyGiftVoucher;
				ApplyGiftVoucher = function() {
					
					fnc.apply(this,arguments);
					
					WellBuilt.formatting.determineTemplate();
				}
			},
			applyTaxRate : function() {
				if (typeof ApplyTaxRate !== 'function') { return; }  
				
				var fnc = ApplyTaxRate;
				ApplyTaxRate = function() {
					
					fnc.apply(this,arguments);
					
					WellBuilt.formatting.determineTemplate();
				}
			},
			clearCart : function() {
				if (typeof ClearCart !== 'function') { return; }  
				
				var fnc = ClearCart;
				ClearCart = function() {
					
					window.alert = function(msg){};
					
					fnc.apply(this,arguments);
					
					WellBuilt.formatting.determineTemplate();
				}
			},
			drawProduct : function() {
				if (typeof DrawProduct !== 'function') { return; }  
				
				var fnc = DrawProduct;
				DrawProduct = function() {
					
					fnc.apply(this,arguments);
					
					WellBuilt.formatting.determineTemplate();
				}
			},
			fixShipping : function() {
				var shippingOptions = document.getElementById('ShippingOptions');
				
				if (shippingOptions) {
					//window.alert = function(msg){};
					shippingOptions.selectedIndex = 1;
					shippingOptions.onchange(); 

					WellBuilt.formatting.determineTemplate();
				}		
			}
		},
		formatting : {
			determineTemplate : function() {
				
				// Initialize Rollovers
				WellBuilt.formatting.initRollovers();
				WellBuilt.formatting.promoRollovers();
				
				// Update Shopping Cart Language
				WellBuilt.formatting.shoppingCartLanguage();				
			
				// Check to see if it is catalog or product and run appropriate functions
				var template = $j.url.segment(0);
				var nontemplate = $j.url.param('ID');
				
				//check for search results off of ID param					
				if (nontemplate == "/search-results.htm") {	
					WellBuilt.formatting.searchFunctions();
				} else if (template != null) {
					var dash = template.lastIndexOf("_");
					var editedTemplate;
					
					(dash > 0) ? editedTemplate = template.substr(0,dash) : editedTemplate = template;
	
						switch(editedTemplate){
		
							case "living":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "dining":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "bedroom":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "workspace":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "outdoor":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "storage":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "lighting":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "accessories":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "_catalog":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.catalogFunctions();
								break;
							case "_product":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.productFunctions();
								break;
							case "CatalogueRetrieve.aspx":
								WellBuilt.formatting.sharedFunctions();
								WellBuilt.formatting.productFunctions();
								break;							
							case "_blog":
								WellBuilt.formatting.aboutFunctions();
								break;
							case "about":
								WellBuilt.formatting.aboutFunctions();
								break;
							case "home.htm":
								WellBuilt.formatting.homepageFunctions();
								break;
							case "OrderRetrievev2.aspx":
								WellBuilt.formatting.checkoutFunctions();
								break;	
						}
					
	
						
					} else {
					WellBuilt.formatting.homepageFunctions();
				}
			},
			sharedFunctions : function() {
				//Remove SubCatalog From catalogueitemdump
				$j("li").remove(":contains('sub-catalogs')");
						
				//Remove no sub catalog error warning
				$j("table").remove(":contains('This catalog has no sub-catalogs.')");			
			
				//manage display of catalogs and subcatalogs and products from breadcrumbs
				if ($j('#breadcrumbs').length > 0) {
				
					var section = $j('#breadcrumbs').text().replace(/ : /,'-');
					var sectionArray = section.split("-");
					
					if ($j('#mainNav').length > 0) {
						var sectionArray1 = sectionArray[0].toLowerCase();
						var currentNav = $j("#mainNav ul li a[href*=" + sectionArray1 + "]");
						$j('body').attr("id" , sectionArray1);							
					}					
					if ($j('#sideNav').length > 0) {
						if (sectionArray[1] != "sub-catalogs" && sectionArray[1] != "sub") {

							$j("#sideNav ul li a:contains('" + sectionArray[1] + "')").addClass("active");
							$j('.living-interior-leftColumn h2').text(sectionArray[1]);
						} 
						// for view all items which are subsub catalogs
						else if (sectionArray[1] == "sub") {
						var sectionArrayArray = sectionArray[2].split(":");
							$j(".secondary-subNav ul li a:contains('" + sectionArrayArray[1] + "')").addClass("active");
							$j('.living-interior-leftColumn h2').text(sectionArrayArray[1]);									
						}
						// for view by designers which are subsub catalogs
						else {					
							$j(".secondary-subNav ul li a:contains('" + sectionArray[2] + "')").addClass("active");
							$j('.living-interior-leftColumn h2').text(sectionArray[2]);				
						}
					}					
				} 
				else if ($j('#mainNav').length > 0) {
					var section = $j.url.segment(0);
					if (section != null) {
						var currentNav = $j("#mainNav a[href*=" + section + "]");
						$j("body").attr("id",section);
					}
				}
			},
			
			searchFunctions : function() {
				
				//console.log('true');
				$j('h4').each(function() {
						
						var carbonProduct = $j(".productitemcell a:contains('Carbon')").text();
						var fullProductTitle = $j(this).text();
						var productArray = fullProductTitle.split("~");
						var productName = productArray[1];
						var productNum = productArray[2];
						var productAtt = productArray[3];
						
						if (productAtt != "noAttr") {
							$j(this).children().text(productName + ": " + productAtt);
						} else {
							$j(this).children().text(productName);
						}
				});					
				
				
				
			},
			
			catalogFunctions : function() {
				// shorten product name to second item in the name - manufac~productName~productNum~productAttr
				if ($j('.productItem h3').length > 0) {
					$j('.productItem h3').each(function() {
						var fullProductTitle = $j(this).text();
						var productArray = fullProductTitle.split("~");
						var productName = productArray[1];
						$j(this).text(productName);
					});	
				}
				//remove empty container div if product div is empty
				if ($j('#interior-rightColumn .living-interior .productfeaturelist').length > 0) {
					$j('.living-interior').each(function() {
						var livingVal = $j(this);
						if ($j(livingVal).children(':last-child').html() == "") {
								$j(livingVal).remove();
						} 
					});					
					$j('ul.productfeaturelist li:nth-child(4)').children(':first-child').css("margin","0px");
					$j('ul.productfeaturelist li:nth-child(8)').children(':first-child').css("margin","0px");					
					$j('ul.productfeaturelist li:nth-child(12)').children(':first-child').css("margin","0px");					
					$j('ul.productfeaturelist li:nth-child(16)').children(':first-child').css("margin","0px");					
					$j('ul.productfeaturelist li:nth-child(20)').children(':first-child').css("margin","0px");					
					$j('ul.productfeaturelist li:nth-child(24)').children(':first-child').css("margin","0px");
					$j('ul.productfeaturelist li:nth-child(28)').children(':first-child').css("margin","0px");
					$j('ul.productfeaturelist li:nth-child(32)').children(':first-child').css("margin","0px");					
					$j('ul.productfeaturelist li:nth-child(36)').children(':first-child').css("margin","0px");
					$j('ul.productfeaturelist li:nth-child(40)').children(':first-child').css("margin","0px");					
				}
				
				
				//Remove SubCatalog From individual catalog layout listing
				$j(".catalogueItem").remove(":contains('sub-catalogs')");
				
				//Edit no products error warning
				if ($j('td.productItemNotFound').length > 0) {
					// check if it displays catalogs(catalogueTable) or products 
					if ($j('.catalogueTable').length == 0) {
						var noProductsMessage = "We are currently pursuing products for this catalog, check back soon.";
						$j('td.productItemNotFound').text(noProductsMessage);
					} else {
						$j('td.productItemNotFound').remove();
					}
				}				
				//Catalog remove system links from H3
				$j('.living-promo h4 a').each(function() {
					$j(this).removeAttr('href');
				});	
			},
			productFunctions : function() {
				
				//printable select options
				if ($j('select').length > 0) {				
					 $("select").each(function(i){
						 var $el = $(this);
						 var $options = $el.find("option");
						 $el.after("<div class='print-select'><ul id=sel"+i+"></ul></div>");
						 var $curPrintBox = $("#sel"+i);
						 $options.each(function() {
							 $curPrintBox.append("<li>"+$(this).text()+"</li>");
						 });    
					 });
					 			 
				}
				// remove please select from printable select options
				$j('li:contains(-- Please select --)').remove();
				
				// shorten product name to second item in the name - manufac~productName~productNum~productAttr
				if ($j('#product-description h2').length > 0) {
						var fullProductTitle = $j('#product-description h2').text();
						var productArray = fullProductTitle.split("~");
						$j('#product-description h2').text(productArray[1]);
				}		
				
				// Apply link to carbon offset http://www.carbonfund.org/
				if ($j("table.productRelatedTable td:contains('Carbon')").length > 0 || $j("table.productRelatedTable a:contains('Carbon')").length > 0) {
					var carbonHTML = $j("table.productRelatedTable td:contains('Carbon')").html();
					var textArray = carbonHTML.split("$");
					$j("table.productRelatedTable td:contains('Carbon')").html(textArray[0] + " <a href=\"http://www.carbonfund.org/\" target=\"_new\">\$" + textArray[1] + "</a>");
				}
				
				// loop throug options and add to select one
				if ($j(".catProdAttributeItem select").length > 0) {
					
					$j(".catProductAttributeGroup").each(function() {
						var selectLabel = $j(this).children(':first-child').text();
						$(this).children(':last-child').children(':first-child').children(':first-child').text(selectLabel);
					});
				}
				
				// change cost display based on option with cost
				
				if ($j(".catProdAttributeItem select").length > 0) {
				
					var productPriceString = $j(".productsRow-price p").text();
					var currentPrice = parseInt(productPriceString.replace(/\$/,'').replace(/,/ig,''));
					
					$j(".catProdAttributeItem select").change(function() {
						
						var currentTotal = 0;
						
							$j(".catProdAttributeItem option:selected").each(function() {
								
								var selectString = $(this).text();
								
								if (selectString.match(/[$]/)) {
									var selectedOptionArr = $(this).text().split("$");
									var selecteOptionNum = parseInt(selectedOptionArr[1]);
									currentTotal += parseInt(selecteOptionNum);
								}
							});
							var revisedPrice = parseInt(currentTotal+currentPrice);
							//.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "")
							$j(".productsRow-price p").text("$" + revisedPrice + ".00");
					});

				}
				
			
				
				//Colorbox
				$j("a[rel='slideshow']").colorbox({transition:"fade"});
			
				//Remove unecessary column
				$j(".living-interior-leftColumn").hide();
				$j(".living-interior").removeClass();	
				$j(".living-interior-rightColumn").removeClass();	
			
				//Move Text from Descriptions to Bottom
				$j('#WhyWellBuiltHolder').html($j('#WhyWellBuiltSource').html());
				$j('#WhyWellBuiltSource').hide();
				$j('#SustainableIconsHolder').html($j('#SustainableIconsSource').html());
				$j('#SustainableIconsSource').hide();
				$j('#ProductDimensionsHolder').html($j('#ProductDimensionsSource').html());
				$j('#ProductDimensionsSource').hide();
			},
			aboutFunctions : function() {
				//make about header active
				$("div.top-hdr-content p:contains('About')").parent().addClass('topHdr-active');
				
				// Active state on sidenav about
				if ($j('#sideNav').length > 0) {
					var section = $.url.segment(1);
					if (section != null) {
						var currentNav = $j("#sideNav ul li a[href*=" + section + "]");
						$(currentNav).addClass("active");
					}
				}
				
				//blog edits
				//add break on date
				$(".blogEntry-leftColumn p").each(function() {
					$j(this).html($(this).html().replace(/, /, "<br>"));
				});
				
				//read more span
				$j(".blogEntry-rightColumn a:contains('READ MORE')").each(function() {
					$(this).wrap('<span class="readMore" />');
				});	
			
				//remove empty pagination
				var pagEmpty = $j("#pagination").html();
				if (pagEmpty == "") {
					$j(".paginationContainer").remove();
				}	
				
				//reveal recent entries
				if ($j('#sideNav').length > 0) {
					var section = $j.url.segment(1);
					if (section != null && section == "News-Press") {
						$j('div.recent-entries').css("display","inline");
					}
				}	
			},
			homepageFunctions : function() {
				$j("#mainPromo-container a").each(function() {								  
					$j(this).removeAttr("href");
				});
				
				$j("#featured-promo1").mouseover(function() {										 
					$j(this).addClass("Over");
					$j('#MainPromo2, #MainPromo3').fadeOut("slow");
					$j('#MainPromo1').fadeIn("slow");
				}).mouseout(function() {
					$j(this).removeClass("Over");
				}).click(function() {
					location.href=$j(this).find("a").attr("href");
				});
			
				$j("#featured-promo2").mouseover(function() {
					$j(this).addClass("Over");
					$j('#MainPromo1, #MainPromo3').fadeOut("slow");
					$j('#MainPromo2').fadeIn("slow");
				}).mouseout(function() {
					$j(this).removeClass("Over");
				}).click(function() {
					location.href=$j(this).find("a").attr("href");
				});
				
				$j("#featured-promo3").mouseover(function() {
					$j(this).addClass("Over");
					$j('#MainPromo1, #MainPromo2').fadeOut("slow");
					$j('#MainPromo3').fadeIn("slow");
				}).mouseout(function() {
					$j(this).removeClass("Over");
				}).click(function() {
					location.href=$j(this).find("a").attr("href");
				});
			},
			checkoutFunctions : function() {
				if ($j("#checkout-purchase").length > 0){
					

					if ($j("input[type=radio]:checked").val() == '5') {
						
							$j("#creditCardRow").hide();
						
						} else {
						
							$j("#creditCardRow").show();							
						
					}					


					$j("input[type=radio]").click(function(){
						if ($j("input[type=radio]:checked").val() == '5') {
						
							$j("#creditCardRow").hide();
						
						} else {
						
							$j("#creditCardRow").show();							
						
						}
					});

					//$j("#tax-row").hide();
			
					//$j("#EmailAddress").change(function() {
					//	$j("#Username").val($j("#EmailAddress").val());
					//});
					
					//$j("#BillingZip").change(function() {
					//	$j("#Password").val("wellbuilt" + $j("#BillingZip").val());
					//	$j("#PasswordConfirm").val("wellbuilt" + $j("#BillingZip").val());
					//});
					
				} else if ($j('.productitemcell a[catid]').length > 0) {
				// shorten product name to second item in the name - manufac~productName~productNum~productAttr and format productAtt
				// ignore catid 27,1663244 - carbon offset and products with no attribute

						
						$j('.productitemcell a[catid]').each(function() {
							
							if ($j(this).attr('id') != 'itemSplit') {
								var carbonProduct = $j(".productitemcell a:contains('Carbon')").text();
								var fullProductTitle = $j(this).text();
								var productArray = fullProductTitle.split("~");
								var productName = productArray[1];
								var productNum = productArray[2];
								var productAtt = productArray[3];
	
								if (productAtt != "" && fullProductTitle!= carbonProduct) {
									//console.log('true');								
									var productAttrNoHyphen = productAtt.replace(/-/gi, " ")
									
									$j(this).html(productName + ": " + productAttrNoHyphen);

								} else if (fullProductTitle == carbonProduct) {
									$j(this).text(carbonProduct);
								} else {
									$j(this).text(productName);
								}
							}
							$j(this).attr('id','itemSplit')
						});	
								
				
				
				}
			},
			uniformSelect : function() {
				//if ($j("select").length > 0) {
				//	$j("select").uniform();
				//}
			},
			
			shoppingCartLanguage : function() {
			
				if ($j("td.cartSummaryItem").length > 0) {
					var cartLanguage = $j("td.cartSummaryItem").text();
					var emptyCart = "Shopping cart is empty.";
					if (cartLanguage == emptyCart) {
						$j("td.cartSummaryItem").html("<a class=\"emptycart\">Cart-0</a>");
					} else if (cartLanguage.substr(0,5) == "Cart-") {
						return;					
					} else {
							var location = $j("td.cartSummaryItem").find("a").attr("href");		
							var cartLanguageHyphen = $j("td.cartSummaryItem").text().replace(/ /,"-");			
							var dash = cartLanguageHyphen.lastIndexOf("-");
							var editedQuantity = cartLanguageHyphen.substr(0,dash);
							$j("td.cartSummaryItem").html('<a href="' + location + '" class="cart">Cart-' + editedQuantity + '</a>');	
					}
				} else if ($j("#catCartSummary").html() == "Your Shopping cart is empty.") {
					$j(".cart-summary").html("<table cellspacing=\"0\" class=\"cartSummaryTable\"><tbody><tr><td class=\"cartSummaryItem\"><a class=\"emptycart\">Cart-0</a></td></tr></tbody></table>");
				}
			
			},
			
			initRollovers : function() {
				var aPreLoad = new Array();
				var sTempsrc;
				var aImages = $j("img,input");
				for (var i = 0; i < aImages.length; i++) {
					if ($j(aImages[i]).hasClass('rollover')) {
						var src = aImages[i].getAttribute('src');
						var ftype = src.substring(src.lastIndexOf('.'), src.length);
						var hsrc = src.replace(ftype, '-over' + ftype);
						aImages[i].setAttribute('hsrc', hsrc);
						aPreLoad[i] = new Image();
						aPreLoad[i].src = hsrc;
						aImages[i].onmouseover = function(){
							sTempsrc = this.getAttribute('src');
							this.setAttribute('src', this.getAttribute('hsrc'));
						}
						aImages[i].onmouseout = function(){
							if (!sTempsrc) 
								sTempsrc = this.getAttribute('src').replace('-over' + ftype, ftype);
							this.setAttribute('src', sTempsrc);
						}
					}
				}
			},
			promoRollovers : function() {
				$j(".top-hdr-content").mouseover(function() {
					$j(this).addClass("Over-topHdr");
				}).mouseout(function() {
					$j(this).removeClass("Over-topHdr");
				}).click(function() {
					location.href=$j(this).find("a").attr("href");
				});
				
				$j(".cart-summary").mouseover(function() {
					var cartText = $(".cartSummaryItem").text();
					if ((cartText != "Shopping cart is empty.") && (cartText != "Cart-0")) $(this).addClass("Over-topHdr");
				}).mouseout(function() {
					$j(this).removeClass("Over-topHdr");
				}).click(function() {
					var cartText = $j(".cartSummaryItem").text();
					if ((cartText != "Shopping cart is empty.") && (cartText != "Cart-0")) location.href=$j(this).find("a").attr("href");
				});
				
				$j(".shop-catalogue").mouseover(function() {
					$j(this).addClass("Over-living");
				}).mouseout(function() {
					$j(this).removeClass("Over-living");
				}).click(function() {
					location.href=$j(this).find("a").attr("href");
				});
				
				$j(".designerColumns").mouseover(function() {
					$j(this).addClass("Over-byDesigner");
				}).mouseout(function() {
					$j(this).removeClass("Over-byDesigner");
				}).click(function() {
					location.href=$j(this).find("a").attr("href");
				});
			}
		}
	};
	
	
	WellBuilt.overrides.addToCart();
	WellBuilt.overrides.updateItemQuantity();
	WellBuilt.overrides.applyDiscountCode();
	WellBuilt.overrides.applyGiftVoucher();
	WellBuilt.overrides.setShippingCountry();
	WellBuilt.overrides.applyTaxRate();
	WellBuilt.overrides.clearCart();
	WellBuilt.overrides.drawProduct();

	
	WellBuilt.formatting.determineTemplate();
	
	WellBuilt.overrides.fixShipping();

});




