var ShoppingCart = {
	// HTML elements
	
	// Helpers
	helpers: { 
		clean: function(str) {
			return str.replace(/[ ]*-*/,'');
		}		
	},
	// Methods
	init: function() {
		ShoppingCart.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'),
			checkoutBtn : $('#checkout a.checkoutBtn'),
			currentQuantity: parseInt($('.currentItemQuantity').text())
		};
		ShoppingCart.getShoppingCart();
		ShoppingCart.getSearchItems();
		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);
			}
		});
	},
	getSearchItems: function() {
		$('.currentItemQuantity').each(function(index){
			if ($(this).text() != 0)
				ShoppingCart.displayCurrentItems(("feedback"+index), ($(this).text()), ((parseInt($(this).text()) == 1)?"item":"items"));
		});
	},
	displayCurrentItems: function(feedbackID, quantity, itemsCopy) {
		var bltParam = typeof blt === "undefined" ? "" : "?blt=" + blt;
		$('#' + feedbackID).html('<div class=\'addedImg\'></div><strong>' + quantity + ' ' + itemsCopy +
				' </strong> successfully added to your cart.<a class=\'checkoutCart\' href=\'/partsdirect/showCart.pd'+ bltParam +'\'\'>Checkout Now</a>');	
	},
	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();
			ShoppingCart.page.checkoutBtn.show();
		}
		if(data.cartItemsList.length == 0) {
			ShoppingCart.page.checkout.show();
			ShoppingCart.page.checkoutBtn.hide();
		}
		
		// 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();
		var element;
		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();
				
				// fixed PD-3483
				ShoppingCart.page.itemTemplate.clone().appendTo(ShoppingCart.page.itemsList).attr('id', partNumberId)
				
				/*element = ShoppingCart.page.itemTemplate.get(0).cloneNode(true);
				element.id = partNumberId;
				
				ShoppingCart.page.itemsList.append($(element));*/
				
				//$(element).appendTo(ShoppingCart.page.itemsList)
				//var s = 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();
		}
		
		if(ShoppingCart.page.currentQuantity != 0)
		{
			ShoppingCart.displayCurrentItems("feedback_is", ShoppingCart.page.currentQuantity, ((ShoppingCart.page.currentQuantity == 1)?"item":"items"));
		}
		
		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
		quantity = ShoppingCart.helpers.clean($('#' + qntIndex).val()) || 1;
		var itemsCopy;
		if (quantity=='1')
			itemsCopy = "item";
		else
			itemsCopy = "items";
		$('#' + feedbackId).html("<div class=\"loaderImg\"></div> Adding <strong>"+ quantity + " " + itemsCopy + " </strong> to your cart");
		$('body').css('cursor','wait');	
		
		
		// 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);
		
			if (futureTotal=='1')
				itemsCopy = "item";
			else
				itemsCopy = "items";
		}
		// Check if it's ok to add to cart		
		if(futureTotal > 999) {
			pathToThickbox = 'itemQuantityLimit.pd?KeepThis=true&TB_iframe=true&height=196&width=300';
			okToAdd = false;
		} else {
			var base_url = window.location.protocol + '//' + window.location.host + '/partsdirect/';
            var bltParam = typeof blt === "undefined" ? "" : "&blt=" + blt;
			if(ShoppingCart.page.itemsCount.text() == 15) {
				pathToThickbox = base_url + 'cartIsFull.pd?KeepThis=true' + bltParam + '&TB_iframe=true&height=325&width=330';
			}
			if(ShoppingCart.page.itemsCount.text() > 15) { 
				pathToThickbox = base_url + 'cartIsReallyFull.pd?KeepThis=true' + bltParam + '&TB_iframe=true&height=320&width=330';
				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); ShoppingCart.displayCurrentItems(feedbackId, (parseInt(futureTotal)), itemsCopy);} });
			if (typeof(oTagger) != "undefined"){
	         	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);
			}
			
			$('body').css('cursor','default');
		}
		
		// User feedback (again)
		$('body').css('cursor','default');
		if(!okToAdd) {
			$('#' + feedbackId).text('Error adding to cart.');
		}
		
		if(pathToThickbox) { 
			tb_show("",pathToThickbox,""); 
		}
	}
};

ShoppingCart.allowAddToCart = false;
