/**
* Product module js.
*
*/
YAHOO.namespace( "cart" );


function initCartAgent()
{
	var cntr = document.getElementById( "cart-summary-container" );
	if ( cntr )
	{
		YAHOO.cart.Agent.Url = decodeURIComponent( document.getElementById( "form-cart-add" ).action );

		YAHOO.cart.Agent.AddBtn = document.getElementById( "to-cart-btn" );
		YAHOO.cart.Agent.CartCounter = document.getElementById( "cart-counter" );
		YAHOO.cart.Agent.NANotice = document.getElementById( "na-notice" );
		YAHOO.cart.Agent.SKU = document.getElementById("sku");
		YAHOO.cart.Agent.Price = document.getElementById("price");

		YAHOO.cart.Agent.SBox = cntr;
		YAHOO.cart.Agent.SBoxProduct = document.getElementById( "prd-name" );
		YAHOO.cart.Agent.SBoxCartTotal = document.getElementById( "cart-summary" );

// 		YAHOO.cart.Agent.check();
	}
	else
		setTimeout( "initCartAgent()", 200 );
}
initCartAgent();


YAHOO.cart.Agent = {

	/**
	* Reference to "Add to Cart" button
	* @var	object
	*/
	AddBtn : null,
	/**
	* Ref. to cart item counter container.
	* @var	object
	*/
	CartCounter : null,
	/**
	* Div container with Not available notice.
	* @var	object
	*/
	NANotice : null,
	/**
	* Price input container.
	* @var	object
	*/
	Price : null,
	/**
	* Cart summary, div container.
	* @var	object
	*/
	SBox : null,
	/**
	* Summary, product name container (div).
	* @var	object
	*/
	SBoxProduct : null,
	/**
	* Summary, cart total info, div container.
	* @var	object
	*/
	SBoxCartTotal : null,
	/**
	* SKU span container.
	* @var	object
	*/
	SKU : null,

	/**
	* URL for Ajax.
	* @var string
	*/
	Url : null,

	/**
	* Add product to shopping cart.
	*
	* @return	void
	*/
	add : function()
	{
		YAHOO.cart.Agent.SBox.style.display = "none";

		var d = YAHOO.cart.Agent.collect();
		d = "add_flag=1" + d;

		var callback = { failure : YAHOO.cart.Agent.failure, success : YAHOO.cart.Agent.addSuccess };

		YAHOO.util.Connect.asyncRequest( "POST", YAHOO.cart.Agent.Url, callback, d );
	},

	/**
	* Check request success callback.
	* Update SKU and price fields.
	*
	* @param	object	o	Response object.
	* @return	void
	*/
	addSuccess : function( o )
	{
		if ( o.responseText.length > 0 )
		{
			var oData = eval( "(" + o.responseText + ")" );
			if ( oData.state == "OK" )
			{
				YAHOO.cart.Agent.SBoxProduct.innerHTML = decodeURIComponent( oData.name );
				YAHOO.cart.Agent.SBoxCartTotal.innerHTML = decodeURIComponent( oData.cart_total );
				YAHOO.cart.Agent.SBox.style.display = "block";

				var items = parseInt( YAHOO.cart.Agent.CartCounter.innerHTML, 10 );
				var qty = parseInt( oData.quantity, 10 );
				var counter = qty + items;
				YAHOO.cart.Agent.CartCounter.innerHTML = counter;
			}
			else if ( oData.state == "NF" )
			{
			}
		}
	},

	/**
	* Make a request to server to check if product
	* with specified options exists.
	*
	* @return	void
	*/
	check : function()
	{
		YAHOO.cart.Agent.Price.value = "";
		YAHOO.cart.Agent.SKU.innerHTML = "";
		YAHOO.cart.Agent.NANotice.style.display = "none";
		YAHOO.cart.Agent.AddBtn.style.visibility = "hidden";

		var d = YAHOO.cart.Agent.collect();

		var callback = { failure : YAHOO.cart.Agent.failure, success : YAHOO.cart.Agent.checkSuccess };
		var url = decodeURIComponent( document.getElementById( "req-url" ).value );
		YAHOO.util.Connect.asyncRequest( "POST", url, callback, d );
	},

	/**
	* Check request success callback.
	* Update SKU and price fields.
	*
	* @param	object	o	Response object.
	* @return	void
	*/
	checkSuccess : function( o )
	{
		if ( o.responseText.length > 0 )
		{
			var oData = eval( "(" + o.responseText + ")" );
			if ( oData.state == "OK" )
			{
				YAHOO.cart.Agent.Price.value = decodeURIComponent( oData.price );
				YAHOO.cart.Agent.SKU.innerHTML = decodeURIComponent( oData.sku );
				YAHOO.cart.Agent.AddBtn.style.visibility = "visible";
			}
			else if ( oData.state == "NF" )
			{
				YAHOO.cart.Agent.Price.value = "";
				YAHOO.cart.Agent.SKU.innerHTML = "";
				YAHOO.cart.Agent.NANotice.style.display = "block";
			}
		}
	},

	/**
	* Closes container according to given ID.
	*
	* @param string Container ID.
	* @return void
	*/
	close : function( id )
	{
		var obj = document.getElementById( id );
		if ( obj && typeof obj.style != 'undefined' ) {
			obj.style.display = 'none';
		}
	},

	/**
	* Collect select product and option data for request.
	*
	* @return	string
	*/
	collect : function()
	{
		var data_str = "", o, i = 1;

		var form = document.getElementById( 'form-cart-add' );
		if ( form ) {
			var tags = ['input', 'select'];
			for ( var i = 0, iMax = tags.length; i < iMax; i++ ) {
				var fields = form.getElementsByTagName( tags[i] );
				if ( fields ) {
					for ( var f = 0, fMax = fields.length; f < fMax; f++ ) {
						if ( fields[f].name != 'price' ) {
							if ( fields[f].tagName.toLowerCase() == 'input' && fields[f].type == 'radio' ) {
								if ( fields[f].checked ) {
									data_str += '&' + fields[f].name + '=' + encodeURIComponent( fields[f].value );
								}
							} else {
								data_str += '&' + fields[f].name + '=' + encodeURIComponent( fields[f].value );
							}
						}
					}
				}
			}

		}

		return data_str;
	},

	/**
	* Request failure callback.
	*
	* @param	object	o	Response object.
	* @return	void
	*/
	failure : function( o )
	{
		alert( o.statusText );
	},

	/**
	* Copy information from billing to shipping fields.
	*
	* @param	object	pCheckbox	The checkbox field triggering the copy.
	* @return	void
	*/
	setShipping : function( pCheckbox )
	{
		var f = pCheckbox.form;
		var names = [ 'name', 'company', 'street', 'city', 'state', 'zip', 'country' ];

		for ( var i in names )
		{
			if ( f.elements['s_'+names[i]] )
			{
				if ( pCheckbox.checked )
				{
					f.elements['s_'+names[i]].value = f.elements['b_'+names[i]].value;
					f.elements['s_'+names[i]].disabled = true;
				}
				else
				{
					f.elements['s_'+names[i]].value = '';
					f.elements['s_'+names[i]].disabled = false;
				}
			}
		}
	},

	/**
	* Make request for getting tax information.
	*
	* @param	string	pUrl	Request url for getting tax info.
	* @return	void
	*/
	tax : function( pUrl )
	{
		if ( document.forms["doc_cart_form"].b_state.value == "CA" ) {
			pUrl += '&sales_tax=1'
		}

		var callback = { failure : YAHOO.cart.Agent.failure, success : YAHOO.cart.Agent.taxSuccess };
		YAHOO.util.Connect.asyncRequest( "GET", pUrl, callback );
	},

	/**
	* Set tax percent, update cart total.
	*
	* @param	object	o	Response object.
	* @return	void
	*/
	taxSuccess : function( o )
	{
		if ( o.responseText.length > 0 )
		{
			var oData = eval( "(" + o.responseText + ")" );
			if ( oData.state == "OK" )
			{
				document.getElementById("sales-tax-1").innerHTML = oData.tax + "%";
				document.getElementById("sales-tax-2").innerHTML = oData.tax + "%";
				document.getElementById("grand-total").innerHTML = oData.grand_total;

				document.getElementById("sales-tax-label-1").style.display = oData.tax > 0 ? "block" : "none";
				document.getElementById("sales-tax-label-2").style.visibility = oData.tax > 0 ? "visible" : "hidden";

				document.getElementById("sales-tax-1").style.display = oData.tax > 0 ? "block" : "none";
				document.getElementById("sales-tax-2").style.visibility = oData.tax > 0 ? "visible" : "hidden";
			}
			else if ( oData.state == "F" )
				alert( "Failed to get tax information." );
		}
	},

	/**
	* Update product quantity and shopping cart total.
	*
	* @param	integer		pPrdId		Product id.
	* @return	void
	*/
	update : function( pPrdId, pOpt, pQty )
	{
		if ( pQty.length > 0 ) pQty = parseInt( pQty, 10 );
		if ( pQty == "NaN" ) pQty = 0;

		var d = "prd_id=" + pPrdId + "&opt=" + encodeURIComponent( pOpt ) + "&quantity=" + pQty;
		var callback = { failure : YAHOO.cart.Agent.failure, success : YAHOO.cart.Agent.updateSuccess };
		var url = decodeURIComponent( document.getElementById( "req-url" ).value );
		YAHOO.util.Connect.asyncRequest( "POST", url, callback, d );
	},

	/**
	* Update request success callback.
	* Update cart (order) total.
	*
	* @param	object	o	Response object.
	* @return	void
	*/
	updateSuccess : function( o )
	{
		if ( o.responseText.length > 0 )
		{
			var oData = eval( "(" + o.responseText + ")" );
			if ( oData.state == "OK" )
			{
				var oTotal = document.getElementById( "subtotal" );
				oTotal.innerHTML = oData.subtotal;

				var itemcount = document.getElementById( "cart-counter" );
				if ( itemcount )
					itemcount.innerHTML = oData.itemcount;
			}
			else if ( oData.state == "F" )
				alert( "Failed to update product quantity." );
		}
	}
}
