/* 
 * This script is to display the total amount in the cart in the top right corner of the page in the static cart. 
 *  1. Get the items in the cart using cart API
 *  2. For each item in the cart ASIN and quantity are got from the cart. 
 *  3. For each ASIN call the product API to get the price of the product. 
 *  4. Calculate product price for quantity and then total of all the items in the cart.  Item price = quantity * price; 
 *  5. Cart Subtotal = subtotal + price;
 *  6. Display the Cart SubTotal to the static cart above. 
 *  Author: Syadavalli 
 */

jQuery(document).ready(function() { 
var asin, quantity, price, subTotal, carTotal, docCookie, endindex, cartID; 
  subTotal = 0; 
if(jQuery.browser.msie != true) {
	//Get cartID from session
	docCookie = document.cookie.toString();
	endindex = docCookie.indexOf(";", docCookie.indexOf("session-id="));
	cartID = docCookie.substring(docCookie.indexOf("session-id=") + 11, endindex);
	//console.log(cartID);
	
	
	
	//1. Get the items in the cart using cart API 
	jQuery.ajax({
		type: 'GET',
		url: '/api/cart/' + cartID + '/items',
		dataType: 'xml',
		async: false,
		success: function(response){
			jQuery(response).find("[nodeName='c:cartItem']").each(function(){
				//2. For each item in the cart ASIN and quantity are got from the cart. 
				asin = jQuery(this).find("[nodeName='c:asin']").text();
				quantity = jQuery(this).find("[nodeName='c:quantity']").text();
				//console.log(asin); 
				//console.log(quantity); 
				
				// 3. For each ASIN call the product API to get the price of the product. 
				var productAPIURL = "http://www.unionbay.com/api/product/asin/" + jQuery.trim(asin);
				jQuery.ajax({
					type: "GET",
					url: productAPIURL,
					dataType: 'xml',
					async: false,
					success: function(productXml){
						price = jQuery(productXml).find("[nodeName='c:any']").find("[nodeName='c:lowestPrice']").find("[nodeName='c:value']").text();
						//console.log(price); 
					}
				});
				
				//4. Calculate product price for quantity and then total of all the items in the cart. 
				price = price * 1 * quantity;
				price = price.toFixed(2);
				//console.log(price);
				
				//5.  Cart Subtotal = subtotal + price;  
				subTotal = (subTotal * 1) + (price * 1);
				subTotal = subTotal.toFixed(2);
				//console.log(subTotal); 
			
			
			
			});
			
			
		}
	});
	
	//6. Display the Cart SubTotal to the static cart above.  
	subTotal = "$" + subTotal.toString();
	carTotal = jQuery.trim(subTotal);
	carTotalTag = '<p id="cartTotal">' + carTotal + '</p>';
	jQuery(".cartInformation").append(carTotalTag);
}
}); 		
					
