var ShoppingCart;
$(document).ready(function() {
	ShoppingCart = {
		// HTML elements
		page: {
			firstItemTemplate: $("#scFirstItemTemplate"),
			itemTemplate: $("#scItemTemplate"),
			itemsCount: $('#scCartItemCount'),
			itemsPlural: $('#scCartItemPlural'),
			itemsCountHeader: $('#scCartItemCountHeader'),
			itemsPluralHeader: $('#scCartItemPluralHeader'),
			itemsList: $("#scItems ul"),
			firstItem: $('#scFirstItem'),
			items: $('#scItems'),
			checkout: $('#checkout'),
			editLink: $('#editLink'),
			scNotice: $('#scNotice')
		},
		// Helpers
		helpers: { 
			clean: function(str) {
				return str.replace(/[ ]*-*/,'');
			}		
		},
		// Methods
		init: function() {
			ShoppingCart.getShoppingCart();
			ShoppingCart.page.checkout.hide();
			ShoppingCart.page.editLink.hide();
			ShoppingCart.page.items.hide();
			ShoppingCart.page.itemsPlural.hide();
			ShoppingCart.page.itemsPluralHeader.hide();
            ShoppingCart.allowAddToCart = true;
		},
		getShoppingCart: function() {
			var cid = '';
			$.each(document.cookie.split(';'), function() {
				if ($.trim(this.split('=')[0]) == 'cid') {
					cid = this.split('=')[1];
				}
			});
			CartAction.getCartDWR(cid,{
				callback: function(data) {
					ShoppingCart.reloadShoppingCart(data);
				}
			});
		},
		reloadShoppingCart: function(data, feedbackId) { 
			// Show checkout button and edit link if we have items
			if (data.cartDaoId != null) {
				setCartCookie(data.cartDaoId, data.cartItemsList.length);
			}
			if(data.cartItemsList.length > 0) {
				ShoppingCart.page.checkout.show();
				ShoppingCart.page.editLink.show();
				ShoppingCart.page.scNotice.show();
			}
			
			// Update item counts on page
			ShoppingCart.page.itemsCount.text(data.cartItemsList.length);
			ShoppingCart.page.itemsCountHeader.text(data.cartItemsList.length);
			
			// Pluralize
			if(data.cartItemsList.length != 1) {
				ShoppingCart.page.itemsPlural.show();
				ShoppingCart.page.itemsPluralHeader.show();
			} else {
				ShoppingCart.page.itemsPlural.hide();
				ShoppingCart.page.itemsPluralHeader.hide();
			}
			
			// Remove all the items to prepare for new list
			$('#currentCart .itemInCart').remove();
			
			for(var itemCount = 0; itemCount < data.cartItemsList.length; itemCount++) {
				// Set image URL
				imageURL = false;
				if(data.cartItemsList[itemCount].part.partImage !== null && data.cartItemsList[itemCount].part.partImage.imageURL !== null) {
					imageURL = data.cartItemsList[itemCount].part.partImage.imageURL + "?$pdth$";
				}
				
				// Set unique id for HTML element
				partNumberId = 'partNumber-' + ShoppingCart.helpers.clean('' + data.cartItemsList[itemCount].part.priceAndAvailability.originalPartNumber + data.cartItemsList[itemCount].part.priceAndAvailability.originalProductGroupId + data.cartItemsList[itemCount].part.priceAndAvailability.originalSupplierId);
				
				// Clone and populate HTML
				if(itemCount == 0) {
					ShoppingCart.page.firstItemTemplate.clone().insertAfter(ShoppingCart.page.firstItemTemplate).attr('id', partNumberId);
					if(imageURL) {
						$("#" + partNumberId + " .scItemImage img").attr('src', imageURL)
						$("#" + partNumberId + " .scItemImage img").attr('alt', "Picture of part");
					} else { 
						$("#" + partNumberId + " .scItemImage").html("<div class='noImageAvailable_small partImage'><a class='partNumber' href='" + "showPart.pd" + data.cartItemsList[itemCount].part.partDetailQString + "' style='display:block; height:36px;' title='click for details'></a></div>");
					}
				} else {
					ShoppingCart.page.items.show();
					ShoppingCart.page.itemTemplate.clone().appendTo(ShoppingCart.page.itemsList).attr('id', partNumberId);
					if(itemCount == data.cartItemsList.length - 1) { 
						$("#" + partNumberId).addClass('last'); 
					}	
				}
				
				$("#" + partNumberId + " .scPartNumber a").text(data.cartItemsList[itemCount].part.partCompositeKey.partNumber)
				$("#" + partNumberId + " .scPartNumber a").attr('href', "showPart.pd" + data.cartItemsList[itemCount].part.partDetailQString)
				//$("#" + partNumberId + " .scDescription").text(data.cartItemsList[itemCount].part.descriptionSentenceCase);
				$("#" + partNumberId + " .scDescription").text(data.cartItemsList[itemCount].part.truncatedExtendedDescription);
				$("#" + partNumberId + " .scQuantity").text(data.cartItemsList[itemCount].quantity);
				$("#" + partNumberId).addClass('itemInCart').show();
			}
			
			// User feedback
			$('#' + feedbackId).text('Added to your cart.');
			$('body').css('cursor','default');
			
			if(data.actionResult === false) {
				alert("There was a problem adding the item to the cart. This part is discontinued.");
			}			
		},
		addToCart: function(commercial, partNumber, productGroupId, supplierId, brandId, documentId, keySuffixId, modelNumber, keyId, pageId, productTypeId, qntIndex, feedbackId) {
            if (!ShoppingCart.allowAddToCart) return;
			// User feedback
			$('#' + feedbackId).text('Adding to cart...');
			$('body').css('cursor','wait');
			
			// Get clean quantity
			quantity = ShoppingCart.helpers.clean($('#' + qntIndex).val()) || 1;
			
			// Set flags
			var inCart = false;
			var okToAdd = true;
			var pathToThickbox = false;				
	
			// Calculate attempted item quantity
			var futureTotal = quantity;
			if($('#partNumber-' + ShoppingCart.helpers.clean('' + partNumber + productGroupId + supplierId)).length) { 
				var inCart = true;
				futureTotal = parseInt($('#partNumber-' + ShoppingCart.helpers.clean('' + partNumber + productGroupId + supplierId) + ' .scQuantity').text()) + parseInt(quantity);
			}
			
			// Check if it's ok to add to cart		
			if(futureTotal > 999) {
				pathToThickbox = 'itemQuantityLimit.pd?KeepThis=true&TB_iframe=true&height=200&width=300';
				okToAdd = false;
			} else {
				var base_url = window.location.protocol + '//' + window.location.host + '/partsdirect/';
				
				if(ShoppingCart.page.itemsCount != null){
                    var bltParam = typeof blt === "undefined" ? "" : "&blt=" + blt;
					if(ShoppingCart.page.itemsCount.text() == 15 && !inCart) {
						pathToThickbox = base_url + 'cartIsFull.pd?KeepThis=true' + bltParam + '&TB_iframe=true&height=240&width=300';
					}
					if(ShoppingCart.page.itemsCount.text() > 15 && !inCart) { 
						pathToThickbox = base_url + 'cartIsReallyFull.pd?KeepThis=true' + bltParam + '&TB_iframe=true&height=240&width=300';
						okToAdd = false;
					}
				}
			}
			
			// Add to cart		
			if(okToAdd) {
			var cid = '';
			if (CookieJar.getCookie('cid')) {
			cid = CookieJar.getCookie('cid');
			}
	         	CartAction.addItemDWR(partNumber, productGroupId, supplierId, brandId, documentId, keySuffixId, modelNumber, keyId, pageId, productTypeId, quantity, cid, { callback: function (data) { ShoppingCart.reloadShoppingCart(data, feedbackId); } });
				oTagger.tag({
					pageName:	"true"==commercial ? 'Commercial Parts > Shopping Cart > Add To Cart' : 'PartsDirect > Shopping Cart > Add To Cart',			
					channel:	'Shopping Cart',
					events:		'scAdd',
					products:	';' + productGroupId + supplierId + partNumber
					});    
				
				//Rich Relevance bottom placement
				if($('#idOfBottomRRDiv')) {
					var rrBottomFrame = $("#rr_bottom").clone();
					rrBottomFrame.attr('src',"/partsdirect/rrPlacement.action?rrPlacement=add_to_cart_page.bottom&itemId=" + productGroupId + supplierId + partNumber);
					rrBottomFrame.css("display","block");
					$('#idOfBottomRRDiv').html(rrBottomFrame);
				}
				
				//Rich Relevance side placement
				if($('#idOfSideRRDiv')) {
					var rrSideFrame = $("#rr_side").clone();
					rrSideFrame.attr('src',"/partsdirect/rrPlacement.action?rrPlacement=add_to_cart_page.side&itemId=" + productGroupId + supplierId + partNumber);
					rrSideFrame.css("display","block");
					$('#idOfSideRRDiv').html(rrSideFrame);
				}				
			}
			
			// User feedback (again)
			$('body').css('cursor','default');
			if(!okToAdd) {
				$('#' + feedbackId).text('Error adding to cart.');
			}
			if(pathToThickbox) { 
				tb_show("",pathToThickbox,""); 
			}
		}
	};
	ShoppingCart.init();
});