/**
 * Functions for manipulating the os commerce cart via javascript.
 * Allows for adding items to the cart including items with attributes.
 * Currently allows for the display of the summary cart.  
 * 
 * Last updated:
 *
 * Author: Sunny Chow
 */

function osc_cart(path)
{
	var me = this;
	me.path = path;
	var pid;

	this.getID = function(idName)
	{
		var pat = /id\[(\d*)\]/;
		var matches = pat.exec(idName);
		return matches[1];
	}

	this.addItemToCart = function()
	{
		// Link that was passed back.  Extract product id.
		pid = $(this).siblings("input[name=products_id]").val();

		var selected = $('select[name^=id]');
		var id = new Object();
		for (var i = 0; i < selected.length; i++)
		{
			var selOptions = $('option:selected', selected[i]);
			// extract the number from id.
			var idNo = me.getID(selected[i].name)
			id[idNo] = selOptions.val();
		}

		$.post(me.path + 'actions.php',
			{ method: "add_to_cart", 
				pid: pid,
			  id : id},
			me.addItemToCartCB);
		$('.cart_status').html('Adding item to cart');
		$('.cart_status').dialog({ buttons: null});
		$('.cart_status').dialog('open');
		$('.cart_status').dialog('option', 'title', '');
		return false;
	}

	this.addItemToCartCB = function(data)
	{
		var retObj = $.parseJSON(data);
		$('.cart_status').html('Kurven indeholder :');
		$('.cart_status').append('<p>' + retObj.product_name );
		if (retObj.options != '')
		{
			for ( var opt in retObj.options)
			{
				$('.cart_status').append('<div style="font-size:.8em;padding-left:1em"><em> - ' + opt + ':' + retObj.options[opt] + '</em></div>');
			}
		}
		$('.cart_status').append('</p>');

		$('.cart_status').dialog('option', 'title', 'Varen er nu lagt i kurven');
		$('.cart_status').dialog(
			{ 
				buttons: { 
					'Køb/se mere cykelgrej' : function() { $('.cart_status').dialog('close'); },
					'Se/rediger indhold i kurv' : function() { window.location = me.path + 'shopping_cart.php'; }, 
					'Betal nu' : function() { window.location = me.path + 'checkout_shipping.php';}
				}
			});
		$('.cart_status').dialog("option", "position", "center");
		me.requestCartContents();
 
	}

	/**
	 * Updates and loads the cart contents
	 */
	this.requestCartContents = function()
	{
		$.get(me.path + 'actions.php?method=get_cart_summary', me.requestCartContentsCB); 
	}

	this.requestCartContentsCB = function(data)
	{
		obj = $.parseJSON(data);

		var count = 0;
		for ( var productName in obj.contents )  
			count += obj.contents[productName].qty;

		var itemStr = 'item';
		if (count > 0)
		{
			if (count > 1) itemStr += 's';
			$(".shopping_cart").css('display',  'block');
			$(".summary").html( count + ' ' + itemStr + ' $' + obj.total );
		}
		
		// Add items to shopping cart dialog box.
		// Clear HTML
		// Look for an infobox where the infoboxHeading is equal to Shopping cart
		var shoppingCart = $('.infoBox').filter(me.id_shoppingcart); 
		var shoppingCartTable = shoppingCart.find('.infoBoxContents').first();
		var text = '';

		// Add Spacing
		text += '<tr><td><img src="images/pixel_trans.gif" border="0" alt="" width="100%" height="1"></td></tr>';

		// Add Items
		text += '<tr><td><table border="0" width="100%" cellspacing="0" cellpadding="0">';
		for (var productName in obj.contents)
		{
			// Add Product Qty
			text += '<tr><td align="right" valign="top" class="infoBoxContents">';
			text += '<span class="';
			text += (obj.contents[productName].updated) ? "newItemInCart" : "infoBoxContents";
			text += '">';
			text += obj.contents[productName].qty;
			text += '&nbsp;x&nbsp;</span></td><td valign="top" class="infoBoxContents">';

			// Add Product No
			text += '<a href=' + me.path + '/product_info.php?products_id=' + productName + '>';
			text += '<span class="';
			text += (obj.contents[productName].updated) ? "newItemInCart" : "infoBoxContents";
			text += '">';
			text += obj.contents[productName].name;
			text += '</span></a></td></tr>';
		}
		text += '</table></td></tr>';

		// Add Line
		text += '<tr><td class="boxText"><img src="images/pixel_black.gif" border="0" alt="" width="100%" height="1"></td> </tr>';

		// Add Total
		text += '<tr><td align="right" class="boxText">';
		text += '<span class="newItemInCart">';
		text += obj.total + '</span></td></tr>'
;
		// Add Spacing
		text += '<tr><td><img src="images/pixel_trans.gif" border="0" alt="" width="100%" height="1"></td></tr>';

		shoppingCartTable.html(text);
	}

	this.id_shoppingcart = function(index)
	{
		// !! Change "Shopping Cart" to your shopping cart title.
		var patShoppingCart = /shoppingcart/;
		if ( $(this).prev() == null || $(this).prev().html() == null)
			return false;

		return $(this).prev().html().match(patShoppingCart);
	}

	// Ids the links that will add the product to cart.
	this.id_links = function(index)
	{
		var patAddToCart = / Tilføj til kurv /;
		return this.title.match(patAddToCart);
	}

	// Initializes the class.
	this.osc_init = function()
	{
			// add to cart link
			$('input').filter(me.id_links).click(me.addItemToCart);

			// add to cart dialog boxes.
			$('body').append('<div class="cart_status" style="display:none"></div>');

			$('.cart_status').dialog(
				{
					"autoOpen":false,
					"draggable":false,
					"resizable":false,
					"modal":true
				}
			);

			// Add mouse over handler to what we added.
			//$('body').append('<div class="cart_contents" style="display:none"></div>');
			//$('.cart_contents').dialog(
			//	{
			//		autoOpen:false,
			//		draggable:false,
			//		resizable:false,
			//		title:'Shopping Cart Contents'
			//	}
			//);
			//var link = $('a', $('#menuNavigation')).filter(function() { return this.href.indexOf('shopping_cart.php') != -1;} );
			//link.mouseover(function() { $('.cart_contents').dialog('open') } );
	}
}


