﻿
function basketUpdate(event)
{
	var x = event.memo.xml;

	var subtotal = $xml(x, "SUBTOTAL");
	
	updateSubTotal(subtotal)
	updateEstimatedShipping($xml(x, "SHIPPING"));
	updateFreeShipping($xml(x, "FREESHIPPING"));

	trace("Begin update each line level elements");
	$A(x.getElementsByTagName("ITEM")).each(function(item){
		trace("Begin sub element procedure");
		var lineitemid = $xml(item, "LINEITEMID");
		trace("Being finding container row");
		var rowContainer = $("div" + lineitemid);
		trace("End finding container row");
		trace("Begin find item sub price");
		var itemSub = rowContainer.down(".subTotal");
		trace("Begin find item price");
		var itemPrice = rowContainer.down(".price");
		var price = new Number();
		trace("Do some math...");
		itemPrice.innerHTML.sub(/\b\d+.\d+\b/, function(match){price = match[0].replace(/\,/g,'');});
		price *= new Number($xml(item, "QTY"));
		trace("Update item sub total");
		itemSub.update("$" + price.toDecimals(2));
		
		rowContainer.down(".fieldTypeOldQuantity").value = $xml(item, "QTY");
		trace("End sub element procedure");
	});
	trace("End update each line level element");
}

function RefreshList(event){
	trace("Finding row");
	var deletedRow = $("div" + event.memo.lineItemID_ToDelete);
	trace("End find row");
	
	updateEstimatedShipping($xml(event.memo.xml, "SHIPPING"));
	updateFreeShipping($xml(event.memo.xml, "FREESHIPPING"));
	
	var effects = new Array(0);	
	new Effect.Opacity(deletedRow, {duration: 1.0, from: 1.0, to: 0.0,afterFinish:function(obj){
		var deletedRow = obj.element;
		deletedRow.remove();
		updateSubTotal($xml(event.memo.xml, "SUBTOTAL"))
	}})
	
}

var alreadyLoggedIn = false;
function moveToFavoritesNotLoggedIn(buttonid)
{
	if(!alreadyLoggedIn)
	{
		document.observe("Login:AddItem", function(event){
			moveToFavorites(buttonid);
			alreadyLoggedIn = true;
			var favContainer = $("divFavMsgContainer");
			favContainer.down(".favoritesText").show();
			var favItemContainer = favContainer.down(".favCount");
			document.observe("Visual:Remove", function(event){
				updateFavoriteCount($xml(event.memo.xml, "FAVORITECOUNT"));
			});
		});

		if(0 >= Ajax.activeRequestCount)
		{
			OpenLogin('/Popup/Login.aspx?r=additem');
		}	
	}
	else
	{
		moveToFavorites(buttonid)
	}
}

function moveToFavorites(buttonid)
{
	trace("moveToFavorites()");
	var aInfo = $(buttonid);
	var xml = "<AJAX><ACTION>MOVETOFAVORITES</ACTION><SKU>" + aInfo.readAttribute("sku") + "</SKU><ITEMID>" + aInfo.readAttribute("itemid") + "</ITEMID><QTY>" + aInfo.readAttribute("qty") + "</QTY><SWATCH>" + aInfo.readAttribute("swatch") + "</SWATCH><FAMILY>" + aInfo.readAttribute("family") + "</FAMILY><CATEGORY>" + aInfo.readAttribute("category") + "</CATEGORY></AJAX>";
	
	PostXML(xml, "/handlers/AjaxShoppingCart.ashx", function(xml){
		var error = $xml(xml, "ERROR");
			if(error == ""){
				$$("body")[0].fire("Visual:Remove", {lineItemID_ToDelete: (aInfo.readAttribute("itemid")),xml: xml});
				updateCartCount($xml(xml, "BASKETCOUNT"));
				updateSubTotal($xml(xml, "SUBTOTAL"));
				updateFavoriteCount($xml(xml, "FAVORITECOUNT"));
				updateEstimatedShipping($xml(xml, "SHIPPING"));
				updateFreeShipping($xml(xml, "FREESHIPPING"));
				trace("Cart item successfully moved to favorites");
			}
		});
}

function updateEstimatedShipping(estimatedShipping)
{
	trace("Update estimated shipping");
	$("divTotalsRightContainer").down("[id$=pFreeShipDiscountValue]").update(estimatedShipping);	
	trace("end estimated shipping");
}

function updateSubTotal(subtotal)
{
	trace("Begin update sub total");
	$("divTotalsRightContainer").down("[id$=basketSubTotal]").update(subtotal);	
	trace("End update sub total");
}

function updateFreeShipping(msg)
{
	trace("Update free shipping");
	$("divTotalsLeftContainer").down("[id$=pOrderLevelFreeShipping]").update(msg);	
	trace("end free shipping");
}

function updateFavoriteCount(count)
{
	trace("begin updateFavoriteCount()");
	var favContainer = $("divFavMsgContainer");
	var favItemContainer = favContainer.down(".favCount");
	favItemContainer.update(count);
	trace("end updateFavoriteCount()");
}

function toggleContinueLinks(elementID,linkID) {
	Effect.toggle(elementID, 'slide', {duration: 0.3});
	
	//TODO swap styles on button to spin the arrow
	//Element.toggleClassName(linkID, 'arrow')l
	//Element.toggleClassName(linkID, 'arrowDown');
}

//_________________________________________________________________________________________________________________
function UpdateQty(redirect)
{
	trace("UpdateQty()");
	var basketItemID = "";
	var sku;
	var qty ="";
	var xml = "";
	var itemCount;
	
	var MessageList = new Array(0);
	
	// Array of all form elements that have a 'class' of 'fieldTypeQuantity'
	trace("Finding text boxes");
	var aryQuantity = $$('input.fieldTypeQuantity');	
	trace("Fidning old quantity hidden field");
	// Array of all form elements that have a 'class' of 'fieldTypeOldQuantity'
	var aryOldQuantity = $$('input.fieldTypeOldQuantity');
	// Array of all input elements that have a 'class' of 'fieldTypeSku'
	trace("Finding sku hidden fields");
	var arySku = $$('input.fieldTypeSku');
	
	// Array of all input elements that have a 'class' of 'fieldTypeLineItemId'
	trace("finding line item id hidden field");
	var aryLineItemId = $$('input.fieldTypeLineItemID');
	
	trace("Finding field type has");
	var aryHas = $$("input.fieldTypeHas");

	// Loop through array of all form elements that have a 'class' of 'fieldTypeQuantity'
	for (var updateCounter=0; updateCounter<aryQuantity.length; updateCounter++)
	{
		//code to be executed
		var fieldValue = aryQuantity[updateCounter].value.strip();
		if(fieldValue == "")
		{
			fieldValue = 0;
		}

		// Make sure quantity is numeric.
		if (!IsNumeric(fieldValue))
		{
			MessageList[MessageList.length] = new ValidationResult(false, "You have entered an invalid quantity.", $$("[clicked]")[0]);
			aryQuantity[updateCounter].value = "";
		}
		// Make sure quantity is greater than 0.
		else if (fieldValue < 0)
		{
			MessageList.push(new ValidationResult(false, "You have entered an invalid quantity.", $$("[clicked]")[0]));
			aryQuantity[updateCounter].value = "";
		}
		//Make sure 'Wants' is not going to be less then 'has'		
		else if ( aryHas.length > 0 && Number($F(aryOldQuantity[updateCounter])) != Number($F(aryQuantity[updateCounter])) && Number($F(aryHas[updateCounter])) > Number($F(aryQuantity[updateCounter])))
		//else if (aryHas.length > 0 && $F(aryHas[updateCounter]) > $F(aryQuantity[updateCounter]))
		{
			MessageList.push(new ValidationResult(false, "The Wants quantity must be greater than or equal to the Has quantity.", $$("[clicked]")[0]));
			aryQuantity[updateCounter].value = $F(aryOldQuantity[updateCounter]);
		}

		// If the above validation tests passed then add the quantity to the CSV string.
		qty = qty + fieldValue;

		// Keep a count of the amount of items with a valid quantity
		itemCount++


	}
	
	//only proceed if the validation passed
	if(MessageList.find(function(result){return !result.valid}))
	{
		DisplayValidation(MessageList, null, null, 'line');
		return;
	}

	for (var updateIndex=0; updateIndex<aryQuantity.length; updateIndex++)
	{
		// Set the quantity value to 0 if the quanitity is empty or less than 0
		if (aryQuantity[updateIndex].value == null || aryQuantity[updateIndex].value  < 0 || aryQuantity[updateIndex].value.strip() == "")
		{
			aryQuantity[updateIndex].value = 0;
		}
		
		//Only include items that have a changed quantity
		if (aryOldQuantity[updateIndex].value != aryQuantity[updateIndex].value)
		{
			xml += "<BASKETDATA>"
					+ "<LINEITEMID>" + aryLineItemId[updateIndex].value + "</LINEITEMID>"
					+ "<SKU>" + arySku[updateIndex].value + "</SKU>"
					+ "<QTY>" + aryQuantity[updateIndex].value + "</QTY>"
					+ "</BASKETDATA>";
		}

    }
    
    if(xml == "")
    {
		if(redirect)
		{
			window.location.href = "/Checkout/Login.aspx";
			return;
		}
		else
		{
			return;
		}
    }

	if (xml.length > 0)
	{
		xml = "<AJAX><ACTION>UPDATEBASKETLIST</ACTION>" + xml + "</AJAX>";
	}
	// Post the xml to the .NET AJAX handler.  If the call was successful the returned xml
	// will be parsed and function "Delegate_UpdateQty" will be called.
	PostXML(xml, "/handlers/AjaxShoppingCart.ashx", function(tree){
			trace("Delegate_UpdateQty()");
			var sku;
			var qty;
			var price;
			var desc;
			var image;
			var family;
			var basketItemID;
			var errorItem;
			var qty;
			//alert('Delegate_UpdateQty');
			// Target the "ITEM" nodes
			var x = tree.getElementsByTagName('ITEM');
			
			trace("Invoking errorpop remove");
			//TODO FOR TEST PURPOSES ONLY --RP 3/19/2008
			$$(".errorpop").invoke("remove");
			trace("End invoke");

			// Loop through each of the "ITEM" nodes and get their child nodes.
			for (i=0; i < x.length; i++ )
			{
				
				lineItemID = ($xml(x[i],"LINEITEMID") != null ? $xml(x[i],"LINEITEMID"): $xml(x[i],"BASKETITEMID"));
				sku = $xml(x[i],"SKU");
				qty = $xml(x[i],"QTY");
				basketType = $xml(x[i],"BASKETTYPE");
				errorItem = $xml(x[i],"ERROR");

				// Update the item's quantity in the visual cart.
				if (errorItem == "NONE")
				{
					if (qty==0)
					{
						trace("Firing Visual:Remove");
						$$("body")[0].fire("Visual:Remove", {lineItemID_ToDelete: lineItemID,activeTab: basketType, xml: tree});
					}
					else
					{
						trace("Firing Visual:Update");
						$$("body")[0].fire("Visual:Update", {lineItemID_ToUpdate: lineItemID,activeTab: basketType, qtyItem: qty, total: (x.length - 1), xml: tree});
					}
					
					updateCartCount($xml(tree, "BASKETCOUNT"));
				}
				else
				{
					//TODO:  We need a better way of alerting the customer that the
					//       item's quantity could not be updated in their shopping cart.
					
					MessageList[MessageList.length] = new ValidationResult(false, "Item's quantity could not be updated.", "StatusMessage");
					DisplayValidation(MessageList);
				}//if/else
			}//for
			
			if(redirect)
			{
				window.location.href = "/Checkout/Login.aspx";
			}
		}//delegate
	);//postxml
}

//_________________________________________________________________________________________________________________
Number.prototype.toDecimals=function(n){
    n=(isNaN(n))?
        2:
        n;
    var
        nT=Math.pow(10,n);
    function pad(s){
            s=s||'.';
            return (s.length>n)?
                s:
                pad(s+'0');
    }
    return (isNaN(this))?
        this:
        (new String(
            Math.round(this*nT)/nT
        )).replace(/(\.\d*)?$/,pad);
}
