// On Pageload

/*
 * hrefID jQuery extention
 */
$.fn.extend({ hrefId: function() { return $(this).attr('href').substr($(this).attr('href').indexOf('#')); } });


/*
 * Scripts
 *
 */
 var MyInterval = 0;
 
jQuery(function($) {
	var Engine = {
		utils : {
			links : function(){
				$('a[rel*=external]').click(function(e){
					e.preventDefault();
					window.open($(this).attr('href'));
				});
			},
			mails : function(){
				$('a[href^=mailto:]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() == mail) {
						$(this).text(replaced);
					}
				});
			},
			fancyBoxInit : function () {                  
				if (typeof $.fn.fancybox == 'function'){

					$('a.fancybox').fancybox(); 
				
					// Fix PopupVideoLink hrefs
					// 
					$('a.popupVideoLink').each(function(i){
						i++
						$(this).attr('href','#video' + i)
					});
					
					// Fancybox for PopupVideoLinks
					$('a.popupVideoLink').fancybox({
						'centerOnScroll': true,
						// avoid closing fancybox with clickable content
						'hideOnContentClick': false,
						// set the fancybox size
						'width':640,
						'height':385,
						'padding':10,
						// avoid video keep playing after
						// fancybox is closed in IE
						'callbackOnClose': function() {
							$('#fancy_content').empty();
						}
					}); 

				}
			}
		},
		fixes : {
			loginCheck : function(){
				if ($('#lchk').text() === '1') {
					$('#sign-in-link').attr('href','/LogOutProcess.aspx');
					$('#sign-in-link span').html('Logout');

					$('#account-link').attr('href','/my-account');
					$('#account-link span').html('My Account');
					$('#account-link1 a').attr('href','/my-account').html('My Account');
                                        $('fieldset.account').css('display','none');
				}
			},
			searchButtons : function () {
				$('#searchprev').addClass('smallButton').html('<span>Previous</span>');
				$('#searchnext').addClass('smallButton').html('<span>Next</span>');
			},
			breadcrumbs : function(){
				$('div.breadcrumbs').contents().each(function(){
					if (this.nodeType === 3 && /[0-9a-zA-Z]+/.test(this.textContent)) {
						$(this).replaceWith(' <span>'+$.trim(this.textContent)+'</span> ')
					}
				});
			},
			mainNavClasses : function () {
				$("#mainNav a").each(function () {
					if($(this).html() === 'For Your Home')
					{
						$(this).parent().addClass('forHome');
					}
					if($(this).html() === 'For Your Self')
					{
						$(this).parent().addClass('forSelf');
					}
					if($(this).html() === 'Kitchen and Tabletop')
					{
						$(this).parent().addClass('kitchen');
					}
					if($(this).html() === 'Bedding and Bath')
					{
						$(this).parent().addClass('bedding');
					}
			//		if($(this).html() === 'Gifts')
			//		{
			//			$(this).parent().addClass('gifts');
			//		}
					if($(this).html() === 'Christmas')
					{
						$(this).parent().addClass('christmas');
					}
					if($(this).html() === 'Valentine\'s Day')
					{
						$(this).parent().addClass('valentines');
					}
					if($(this).html() === 'Easter and Spring')
					{
						$(this).parent().addClass('easter');
					}
					if($(this).html() === 'Mother\'s Day Gift Ideas')
					{
						$(this).parent().addClass('mothers-day');
					}
					if($(this).html() === 'Graduation Gift Ideas')
					{
						$(this).parent().addClass('graduation');
					}
					if($(this).html() === 'Summer Essentials')
					{
						$(this).parent().addClass('summer');
					}
					if($(this).html() === 'Wall Decor')
					{
						$(this).parent().addClass('wall-decor');
					}
					if($(this).html() === 'Fall Collection')
					{
						$(this).parent().addClass('fall');
					}
					if($(this).html() === 'New Arrivals')
					{
						$(this).parent().addClass('new-arrivals');
					}
				});
			},
			ecommBreadcrumbs :function () {
				if($('#bc-to-copy').length)
				{
					var text = $('#bc-to-copy').html();
					text = text.replace(/:/g, "");
					$('div.breadcrumbs').append(text);
					$('#bc-to-copy').remove();
				}
			},
			activeNav : function(el,activeClass){
				$(el).find('li a').each(function(){
					var path = document.location.href;
					var current_href = this.getAttribute('href',2);
					if (path.split(".com")[1] == current_href) {
					  $(this).addClass(activeClass);
					  $(this).parents("li").addClass(activeClass);
					}
				});
			},
			activeNavFromBcrumbs : function(el, activeClass, bcrumbIndex){
				if($('div.breadcrumbs a').length-1 >= bcrumbIndex)
				{
					var myHost = document.location.protocol+'//'+document.location.hostname;					
					var path = $('div.breadcrumbs a').eq(bcrumbIndex).attr('href');					
					path = path.replace(myHost, '');					
					$(el).find('li a').each(function(){
						var current_href = this.getAttribute('href',2);	
						current_href = current_href.replace(myHost, '');
						if (path == current_href) {
						  $(this).addClass(activeClass);
						  $(this).parents("li").addClass(activeClass);
						}
					});
				}
			},
			ecommPagination : function () {
				if($('.shopContent div.pagination').length)
				{
					$('.shopContent div.pagination a').each(function () {
						$(this).addClass('smallButton').html('<span>'+ $(this).html() +'</span>');
					});

					$('span#pagination').contents().each(function(){
						if(this.nodeType === 3 && (/[0-9]+/.test(this.textContent) || /[0-9]+/.test(this.toString()))) {								
							var myString = $.trim(this.textContent);
							if(!/[0-9]+/.test(this.textContent))
							{
								myString = this.toString();
							}
							$(this).replaceWith('<strong class="smallButton"><span>'+myString+'</span></strong>');
						}
					});				
				}
			},
			ecommSideMenu : function () {
				if($('.shopContent #secondaryBody').length)
				{
					$('#secondaryBody .catalogueitemdump').eq(0).addClass('sideNav');
					$('#secondaryBody .sideNav').eq(1).addClass('second');
					$('#secondaryBody .catalogueitemdump').eq(0).find('a').each(function () {
						$(this).html('<h3>'+$(this).html()+'</h3>');
					});

					$('#secondaryBody .catalogueitemdump').eq(0).find('a').each(function () {
						var path = $(this).attr('href');
						var id = "#"+path.split("/")[1];
						if($(id).find('li').length)
						{
							var submenu = $(id).html();
							$(this).parent().append(submenu);							
						}
					});
				}
			},
			emptyLists : function(){
				$('.shopContent li.catalogueItemNotFound').each(function(){
					$(this).parent().remove();
				});

				$('.shopContent li.productItemNotFound').each(function(){
					$(this).parent().remove();
				});

				//remove product list if we are on the main catalog page
				if ($('.shopContent li.catalogueItem').length > 0 && $('.products-a ul li.productItemNotFound').length > 0) {
					$('.products-a').remove();
				}
			},
			catalogList : function () {
				var l = window.location+'';
				if (l.indexOf('_product_') !== -1 || l.indexOf('product.html') !== -1 || l.indexOf('ProductID') !== -1) {
					return;
				}


				$('ul.catalogueList').addClass('productList').removeClass('catalogueList');
				$('div.shop-catalogue img, .productSmall img').parent('a').addClass('pImage');


				if($('.productList').length > 1)
				{
					var elements = $('.productList li').clone();
					$('ul.productList').remove();
					//elements.wrapAll().
					$('#primaryContent h1').after('<ul class="productList"></ul>');
					$('ul.productList').append(elements);
				}


				//remove empty itemNotes
				$('.itemNote').each(function () {
					if(!$(this).html())
					{
						$(this).remove();
					}
				});

			},
			productDetails : function(){

				var l = window.location+'';
				if (l.indexOf('_product_') === -1 && l.indexOf('product.html') === -1 && l.indexOf('ProductID') === -1) {
					return;
				}

				//clone the main product container with thickbox events
				var productDetails = $('#product-details').clone(true);
				
				//change content class
				$('#content').removeClass('shopContent').addClass('productContent');

				//remove useless content
				$('#content div.primary').remove();
				$('#content div.secondary').remove();
				
				//insert product content
				$('#content').append(productDetails);
				
				//get last bcrumb item and insert into "<h2 class="pSeries">"
				var text = $('.breadcrumbs a:last-child').html();
				$('h2.pSeries').html(text);

				//add-to-cart button
				var button = $('#add-to-cart-input').html();
				button = button.replace(/input/gi, "span");
				button = button.replace(">", ">Add to your bag</span>");
				button = button.replace('value="Add to Cart"', "");
				button = button.replace('type="submit"', "");

				$('#addToBag').html(button);
				$('#add-to-cart-input').remove();

				$('#addToBag').click(function () {
					Engine.fixes.cart();
				});
				
				$('#addToBag').after('<div class="hr"><hr /></div><p id="pDesc"><a name="fb_share" type="button_count" href="http://www.facebook.com/sharer.php">Share on Facebook</a><script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script></p>');

				//IMAGES

								
//				var bigThumbSrc = '/Utilities/ShowThumbnail.aspx?W=338&H=416&R=1&F=True&Img=';
				var bigThumbSrc = '';
				
				//popplets
				$('td.productPopletsItem a').removeAttr('onclick');
				$('td.productPopletsItem a').removeAttr('rel');

				var popplets = $('td.productPopletsItem a').clone();

				$('#pImageThumbnails table').remove();
				$('#pImageThumbnails').append(popplets);
				$('#pImageThumbnails a').wrap('<li></li>');
				$('#pImageThumbnails li').eq(0).addClass('active');

				$('#pImage #loader').remove();
				
				$('#pImageThumbnails a').click(function (e) {
					e.preventDefault();
					
					$('#pImage #loader').remove();
					
					if($('#pImage img').attr('src') == $(this).attr('href'))
					{						
						return false;
					}					
					
					var imgPath =  $(this).attr('href');
					$('#pImage').attr('href', imgPath);
					$('#pImage img').attr('src', bigThumbSrc+imgPath);
					$('#pImageThumbnails li').removeClass('active');
					$(this).parent().addClass('active');	
					
					var isIE6 = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 7);
					
					//preloader
					var imgPreloader = new Image();
					imgPreloader.src = imgPath;
					
					$('#pImage').append('<span id="loader"></span>');
					
					if(isIE6) {
						$('#pImage #loader').height($('#pImage').height());
					}         
					
					$('#pImage #loader').fadeTo("fast", 1);				
										
					var MyInterval = window.setInterval(function(){
						if (imgPreloader.complete === false) {
							return;
						}
						
						$('#pImage #loader').fadeOut("fast", function () {
							$('#pImage #loader').remove();									
						});
						
						clearInterval(MyInterval);
						
					}, 100);				
				});
				
				//main image
				var imageSource = $('#pImage img').attr('src');
				$('#pImage').attr('href', imageSource);
				var newSrc = bigThumbSrc+imageSource
				$('#pImage img').attr('src', newSrc);				
				

				//related products
				if($('.relatedProducts td').length)
				{
					$('.relatedProducts td').each(function (i) {
						if(i < 3)
						{
							var name = $(this).find('h3.itemName a').html();
							$(this).find(' > a').prepend('<span>'+name+'</span>');
							$(this).find(' > a img').attr('width', 90).attr('height', 90);
							$(this).find(' > a').appendTo('.relatedProducts');
							//alert(name);
						}
					})
					$('.relatedProducts table').remove();
					$('.relatedProducts a').wrap('<li></li>');
				}
				else
				{
					$('.relatedProducts').remove();
				}
			}, 
			cart : function() {
				//change cart text info in header options 
				if ($('#catCartSummary .cartSummaryItem').html() != 'Shopping cart is empty.') {
					var summary = $('#catCartSummary .cartSummaryItem').text();
					summary = summary.replace("Total: ", '');
					summary = summary.replace("View Cart", '');
					$('#utilityNav .cartSummary a').text(summary);//.addClass('items');
					
					//attempted fix for cart issue. left for possible future use 2011-08-31 sb
					//var cartUrl = $('a.cartSummaryLink').attr('href');
					//$('div.cartSummary a').attr('href',cartUrl);
				}
				
				$('#goback a').attr('href',document.referrer);
          
				Engine.fixes.emptyCartMessage(); 
				
				if (typeof ClearCart !== 'function'){
					return;
				}
				
				var _ClearCart = ClearCart;
				var _alert = window.alert;
				ClearCart = function(){   
					//disable alert
					window.alert = function(){};

					_ClearCart.apply(window,arguments);
					
					Engine.fixes.emptyCartMessage(); 
					//reenable alers
					window.alert = _alert;						
				}
			},
			//change "Shopping cart is empty. Go Back" on cart page			  
			emptyCartMessage : function(){
				$("#catCartDetails a.cartLink:contains('empty')").html('Your bag is empty. Go back').attr('href', '/');
			},
			shipping : function(){
				if (typeof UpdateShipping !== 'function'){
					return;
				}     
				
				var _UpdateShipping = UpdateShipping;
				var _alert = window.alert;
				UpdateShipping = function(){   
					//disable alert
					window.alert = function(){};

					_UpdateShipping.apply(window,arguments);
					
					//reenable alers
					window.alert = _alert;						
				}
			},
			blogPagination : function(){
				if($('#blog').length)
				{
					var styleAttr = $('#blog #previouspage').attr('style');
					if( styleAttr.indexOf('inline') != -1)
					{
						$('#blog #previouspage').removeAttr('style');
					}

					var styleAttr1 = $('#blog #nextpage').attr('style');
					if( styleAttr1.indexOf('inline') != -1)
					{
						$('#blog #nextpage').removeAttr('style');
					}

					if(styleAttr.indexOf('display: none;') != -1 && styleAttr1.indexOf('display: none;') != -1)
					{
						$('#blog .pagination').hide();
					}
					else
					{
						$('span#pagination a').each(function () {
							$(this).addClass('smallButton').html('<span>'+ $(this).html() +'</span>');
						});

						$('span#pagination').contents().each(function(){
							if(this.nodeType === 3 && (/[0-9]+/.test(this.textContent) || /[0-9]+/.test(this.toString()))) {								
								var myString = $.trim(this.textContent);
								if(!/[0-9]+/.test(this.textContent))
								{
									myString = this.toString();
								}
								$(this).replaceWith('<strong class="smallButton"><span>'+myString+'</span></strong>');
							}
						});

						$('#nextpage').addClass('smallButton').html('<span>Next</span>');
						$('#previouspage').addClass('smallButton').html('<span>Previous</span>');
					}
				}
			},
			continueShoppingBtn : function (){
			
			$("#catshopquote").attr("href","/_catalog_61080/For_Your_Home");
			
			},
			blog : function(){
				if($('#blog').length)
				{
					// show/hide comments/trackbacks
					var $links = $('#blog a.comments, #blog a.trackbacks');
					$links.click(function(){
						$($(this).hrefId()).toggle();
						if($(this).is('.comments')) $($(this).hrefId()).next().next('div.add-comment:first').toggle();
						return false;
					});

					// single post (show trackbacks and comments)
					if($('div.entry').length == 1){
						$('div.trackbacks, div.add-comment, div.comments').show();
					}
					// single post (hide comments when there are none)
					$("div.comments:contains('Post has no comments')").hide();
					$('#blog .meta').after('<p id="pDesc"><a name="fb_share" type="button_count" href="http://www.facebook.com/sharer.php">Share on Facebook</a><script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script></p>');
				}
			},
				checkout : function(){
				// -----------------------------------------------------
				// This will copy over the shipping address value to the 
				// billing address.  Make sure the checkbox Id is "SameAsShipping"
				// -----------------------------------------------------	
				$("#SameAsShipping").bind("change", function(e){
					if($(this).checked){
						// unchecked
					}else{
						// checked
						$("#BillingAddress").val($("#ShippingAddress").val());
						$("#BillingCity").val($("#ShippingCity").val());
						$("#BillingState").val($("#ShippingState").val());
						$("#BillingZip").val($("#ShippingZip").val());
						
					}
				});	
			
				// ------------------------------------------------------
				// This sets an html element with id of #order-summary-value 
				// with the $500.00, so the $ plus the amount.  This allows
				// you to style that container and merely hide the amount
				// input form element.
				//-------------------------------------------------------
				$('#order-summary-value').text($('input#Amount').val());
			
				// ------------------------------------------------------
				// This will prevent Credit card information from being 
				// collected if the purchase amount is zero.  It means 
				// that either a discount code or gift voucher was used.
				// Make sure to wrap the entire credit card area with a 
				// container id of #credit-card-information
				//-------------------------------------------------------
				if ($('input#Amount').val() === '0.00') {
					$('#PaymentMethodType_9').attr('checked','checked');
					$('#credit-card-information').css('display','none');	
				}
			},
			galleryPagination : function () {
				if($('#gallery-container').length)
				{
					if(!$('ul.gallery').hasClass('no-pagin'))
					{
						var pagination = $('ul.gallery ul.pagination').clone();
						$('#gallery-container').append(pagination);
						$('ul.gallery ul.pagination').remove();
						$('#gallery-container ul.pagination a').addClass('smallButton').wrapInner('<span></span>');
						$('#gallery-container ul.pagination li.pag-current').wrapInner('<strong class="smallButton currentPaginationItem"><span></span></strong>');
					}
				}
			},   
      updateLink : function(){	                
				
				window.setInterval(function(){
					if ($('tbody tr.val td.update-box a').length > 0) {
						return;
					} 
					
					$('tbody tr.val td:first div').each(function(){     
						$('tbody tr.val td.update-box').append('<div class="productitemcell"><span><a href="#">update</a></span></div>')
					});      
					
					$('tbody tr.val td.update-box a').click(function(e){
						e.preventDefault();
					});										
				}, 50);				
			},
			addToCart : function(){
				if ($('#addToBag').length === 0 || typeof AddToCart !== 'function') {
					return;
				}        
				
				var fnc = AddToCart;        
				var _alert = window.alert;
				AddToCart = function(){
					
					window.alert = function(msg){
						var p = $('<p class="alertMessage">'+msg+'</p>');
						$('#addToBag').after(p);
						
						window.setTimeout(function(){
							p.fadeOut('slow', function(){
								p.remove();
							});
						}, 3000);
					};
					
					fnc.apply(this,arguments);
					
					window.alert = _alert;
				};
			},
			validateCart : function(){

				if ($('#catshopbuy').length === 0 || typeof ValidateCart !== 'function'){
					return;
				}
								
				var _alert = window.alert;
				var fnc = ValidateCart;
				
				ValidateCart = function(){  
					window.alert = function(msg){      
						if (msg === 'ERROR: Please choose a valid shipping option.') {
							var p = $('<p class="alertError">'+msg+'</p>');
						
							$('#ShippingOptions').after(p);
							window.setTimeout(function(){
								p.fadeOut('slow',function(){
									p.remove();
								});
							}, 3000);
						}   
						else if (msg === 'ERROR: Please choose a destination state to calculate state tax.') {
							var p = $('<p class="alertError">'+msg+'</p>');
						
							$('#shippingState').after(p);
							window.setTimeout(function(){
								p.fadeOut('slow',function(){
									p.remove();
								});
							}, 3000);							
						}
						else if (msg === 'ERROR: Please enter in your Zip/Postcode to calculate shipping costs for your order.') {
							var p = $('<p class="alertError">'+msg+'</p>');
						
							$('.shippingPostcodeDiv').after(p);
							window.setTimeout(function(){
								p.fadeOut('slow',function(){
									p.remove();
								});
							}, 3000);							
						}						
						else {
							_alert(msg);
						}
					};
					
					var res = fnc.apply(this,arguments);
					
					window.alert = _alert;
					
					return res;
				};
			},
			noRightClick : function(){
				$(document).bind("contextmenu",function(e){
					return false;
				});	
			}

		}
	};

	Engine.fixes.loginCheck();
	Engine.utils.links();
	Engine.utils.mails();
	Engine.fixes.mainNavClasses();
	Engine.fixes.ecommBreadcrumbs();
	Engine.fixes.breadcrumbs();

	Engine.fixes.ecommSideMenu();
	Engine.fixes.activeNavFromBcrumbs("#secondaryContent .catalogueitemdump","active", 1);
	Engine.fixes.activeNavFromBcrumbs("#mainNav ul","active", 1);
	Engine.fixes.activeNavFromBcrumbs("#secondaryContent .catalogueitemdump li.active ul","selected", 2);
	Engine.fixes.emptyLists();
	Engine.fixes.productDetails();
	Engine.fixes.catalogList();
	Engine.fixes.ecommPagination();
	Engine.fixes.cart();
  Engine.fixes.shipping();
	Engine.fixes.searchButtons();

	Engine.fixes.blog();
	Engine.fixes.blogPagination();

	Engine.fixes.galleryPagination();

	Engine.utils.fancyBoxInit();
	
	Engine.fixes.continueShoppingBtn();
	Engine.fixes.checkout();

  Engine.fixes.updateLink();

	Engine.fixes.addToCart();
	
	Engine.fixes.validateCart();
Engine.fixes.noRightClick();
});

// Popup

function wopen(url) {
	w = 600;
	h = 400;
	wleft = (screen.width - w) / 2;
	wtop = (screen.height - h) / 2;	
	newwindow=window.open(url,'name','width=' + w + ',height=' + h + ',left=' + wleft + ',top=' + wtop + ',location=yes,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes');
	if (window.focus) {newwindow.focus()}
	return false;
}

$(document).ready(function(){
	$(".catalogueitemdump.sideNav li:last-child").addClass('giftCards');
});
