var minicartActive = true;
var minicartActive = true;

/**
 * @author bradleyc
 */
GSI.NameSpace.create("GSI.Minicart");

GSI.Minicart.loadingHTML = '\
	<div style="margin-bottom:6px;font-size:14px;font-weight:bold">Loading Minicart</div>\
	<img src="/images/prodDetails/loader.gif" />';

GSI.Minicart.minicartDiv = $("minicart");

/**
 * Add to cart via AJAX
 * @param {Form Element} 	formObject		The "add to cart" form object
 * @param {String} 				prodDisplay		Custom flag string for URL 	
 */
GSI.Minicart.ajaxAddToCart = function(formObject, prodDisplay)
{
	if( $("minicart") == null ) GSI.$e("div", "minicart", "minicart", false, document.body);
	
	var div = $("minicart");
	if( GSI.Application && GSI.Application.Dockers &&	GSI.Application.Dockers.ExpressShop ) GSI.LightBox.close();
	
	GSI.StatusMessage.setStatus( "Loading Minicart...", true );
	GSI.Position.recenter();
	GSI.StatusMessage.setVisibility(true);
	
	var url = "/cartHandler/index.jsp";
	var pars = "";
	
//	Handle unsupported browser versions
	if( GSI.Browser.is("IE") && GSI.Browser.version == "5.2" )
	{
		formObject.submit();
		return;
	}

//	Set the URL for custom prodDisplays
	if(prodDisplay == "docGiftCert") url = "/giftCertificates/customHandler.jsp";

//	Loop through the form elements and add as parameters
	for(var i=0;i < formObject.elements.length;i++)
	{
		var elem = formObject.elements[i];
		if( elem.type == 'checkbox' && !elem.checked ) break;
		pars += elem.name + "=" + elem.value + "&";
	}

// make sure the carthandler knows its getting an async call.
	pars += 'async=true'; 
	var myAjax = new Ajax.Request( url, 
		{	
			method: 'post', 
			parameters: pars, 
			onSuccess: GSI.Minicart.ajaxSuccess, 
			onFailure: GSI.Minicart.ajaxFailure,
			onException: GSI.Minicart.ajaxException
		}
	); 
}

/**
 * Update the cart item display
 * @param {Object} itemCount
 */
GSI.Minicart.updateCartItemDisplay = function( itemCount )
{
	var n = $("es_productQuantity");
	var nCopy = $("cartCountCopy");
	// this document node might not exist everywhere
	if (n)
	{
		n.innerHTML = itemCount;
	}
	
	if (nCopy)
	{
		if (itemCount == 1)
		{
			nCopy.src = "/images/topnav_items04_singular.gif";
		}
		else if (itemCount == 0 || itemCount > 1)
		{
			nCopy.src = "/images/topnav_items04.gif";
		}
	}
}

/**
 * Handle AJAX call success from addToCart
 * @param {Object} transport
 */
GSI.Minicart.ajaxSuccess = function( transport )
{
	GSI.StatusMessage.setVisibility(false);
	
//	Scroll to the top to see the minicart
	scroll(0,0);
	
//	Get the response text
	var txt = transport.responseText;
	
//	Check for success code sent from server
	if (txt.indexOf("AJAX_SUCCESS") > -1)
	{
		var itemCount = getXmlValue(txt,"itemCount");
		GSI.Minicart.updateCartItemDisplay( itemCount );
		//getOrderItemDetails();
		getOrderItemDetails(getXmlValue(txt, "skusAdded"), getXmlValue(txt, "qtyAdded"));
	}
//	Otherwise redirect to the error page passed back
	else
	{
		window.location = getXmlValue( txt, 'rdir' );
	}
}

/**
 * Handle AJAX exceptions...
 * @param {Object} request
 * @param {Object} exception
 */
GSI.Minicart.ajaxException = function( request, exception )
{
	document.orderForm.submit();
	GSI.LightBox.close();
}

/**
 * Handle AJAX call failure from addToCart
 * @param {Object} transport
 */
GSI.Minicart.ajaxFailure = function( transport )
{
	document.orderForm.submit();
	GSI.LightBox.close();
}

/**
 * Get order item details
 */
GSI.Minicart.getOrderItemDetails = function(skusAdded, qtyAdded)
{
// Append a timestamp to prevent caching of the response.
	var myAjax = new Ajax.Request( '/minicart/index.jsp', 
		{ 
			method: 'get', 
			parameters: 't=' + new Date().getTime() + '&skusAdded=' + skusAdded + '&qtyAdded=' + qtyAdded, 
			onSuccess: GSI.Minicart.updateCart,
			onFailure: GSI.Minicart.ajaxFailure,
			onException: GSI.Minicart.ajaxException
		}
	);
}

/**
 * Handle AJAX call success from getOrderItemDetails
 * @param {Object} transport
 */
GSI.Minicart.updateCart = function( transport )
{
//	Get the response text from the AJAX call
	var txt = new String( transport.responseText );
	var div = $("minicart");
		
	Element.update(div, txt );
	Element.show(div);
	toggleSelects("hideSelects");
	
// run any scripts that might be in the minicart html, mainly this ensures that omniture reporting works
	txt.evalScripts();
}

/**
 * Toggle the selects in the form
 * @param {String} toggleMode
 */
GSI.Minicart.toggleSelects = function( toggleMode )
{
// TODO: Why are we doing this based off of ie?
//	if (navigator.appVersion.indexOf("MSIE")!=-1)
	if( GSI.Browser.is("IE"))
	{
		var s = document.getElementsByTagName("select");
		
		if (toggleMode == "hideSelects")
		{
  		for (var i=0; i<s.length; i++) 
			{
    		s[i].style.visibility = "hidden";
  		}
		}
		else
		{
			for (var i=0; i<s.length; i++) 
			{
    		s[i].style.visibility = "visible";
  		}
		}
	}
}

/**
 * Returns the value of a node "nodeName" within the XML text "xmlText"
 * @param {String} xmlText	The XML text to search within		
 * @param {String} nodeName	The node to search for
 */
GSI.Minicart.getXMLValue = function( xmlText, nodeName )
{
//	Match the beginning node by name
	var pattern = 	"<\\s*" + nodeName + "\\s*>";
//	Get the text within the node
			pattern += "([\\n\\r\\t\\v\\f\\d\\D\\w\\W\\s\\S]*)";
//	Match the close node
			pattern += "<\\s*/\\s*" + nodeName + "\\s*>";
	
	var result = new RegExp( pattern ).exec( xmlText );
	return ( result == null ) ? "" : result[1]; 
}

/**
 * Hide the minicart
 */
GSI.Minicart.hide = function()
{
	Element.hide('minicart');
	toggleSelects('showSelects');
}

//----------------------------------------------------------------
//	Set aliases for GSI.Minicart methods
var ajaxAddToCart = GSI.Minicart.ajaxAddToCart;
var getOrderItemDetails = GSI.Minicart.getOrderItemDetails;
var toggleSelects = GSI.Minicart.toggleSelects;
var getXmlValue = GSI.Minicart.getXMLValue;
var hideCart = GSI.Minicart.hide;
var updateCartItemDisplay = GSI.Minicart.updateCartItemDisplay;