
/**
 * shoppingCart
 * 
 * Class to add and removes items from the shooping cart via ajax. [dom] is the 
 * id of an DOM element where the shopping card is displayed
 * 
 * <code>
 * shoppi€ngCart = new shoppingCart('[dom]');
 * 
 * shoppingCart.addItem({pid: 2198, slots: 16, period: 6});
 * 
 * shoppingCart.removeItem(3);
 * </code>
 * 
 * @author bob
 */
function shoppingCartItem(id, displayList)
{
	this.url = orderClientGW;
	this.id = id;
	this.displayList = displayList;

	this.showCart = function(){

		if($('#' + this.id).length > 0)
		{
			$('#' + this.id + 'Box' ).hide();
			//$('#' + id).html('<p>Loading ...</p>');
			
			this.loadCart();
		}

	}

	this.loadCart = function(){

		var req_url;

		if(this.displayList)
		{
			req_url = this.url + '?action=getShoppingCart&list=true';
		}
		else
		{
			req_url = this.url + '?action=getShoppingCart';
		}
		
		$.get(req_url, function(data){

			$('#' + id).html(data);
			if ($('#' + id + ' li').length > 0) {
				$('#' + id + 'Box').slideDown('fast');
			}

			$.unblockUI();

		});

	}
	
	this.setCart = function(data){
			$('#' + id).html(data);
			if ($('#' + id + ' li').length > 0) {
				$('#' + id + 'Box').slideDown('fast');
			}

			$.unblockUI();
	}


	this.addItem = function(data){

		$.blockUI({ message: $('#loading') });

		var append;
		if(this.displayList)
		{
			append = '&list=true';
		}
		else
		{
			append = '';
		}
		
		$.ajax({

			type: 'POST',
			url: this.url + '?action=addItem'+append,
			data: data,
			context: this,
			success: function(response){
					this.setCart(response);
					window.location.href = this.url + '?step=1';
			}

		});
		return false;

	}

	this.removeItem = function(kitem){

		$.blockUI({ message: $('#loading') });

		$.ajax({

			type: 'GET',
			url: this.url + '?action=deleteItem&kitem=' + kitem,
			context: this,
			success: function(data){
				this.setCart(data);
			}

		});
		
		if (typeof _gaq == 'object') { 
			_gaq.push(['_trackEvent', 'orderform', 'remove_from_basket']);
		}

		return false;

	}

	// load the shoppingcart
	if (displayList) {
		this.showCart();
	}
}

/**
 * addProduct
 * 
 * Function to add items from a form to the shoppingcart
 * 
 * @param string formId
 * @return void
 */
function addProduct(formId)
{
	formId = typeof formId != 'undefined' ? formId : 'formAdd';

	var values = $('#' + formId).serializeArray();
	var obj = {};

	for(var i = 0; i < values.length; i++)
	{
		obj[values[i].name] = values[i].value;
	}
	if (typeof _gaq == 'object') { 
		_gaq.push(['_trackEvent', 'orderform', 'product_to_basket']);
	}
	shoppingCart.addItem(obj);
	
}

/**
 * loadForm
 * 
 * @param pid
 * @return void
 */
function loadForm(pid)
{
	$.get(orderClientGW + '?action=getForm&pid=' + pid, function(data) {
		$('#form').html(data);
		$.blockUI({ message: $('#form'), css: { cursor: 'default' } });
	});
	if (typeof _gaq == 'object') { 
		_gaq.push(['_trackEvent', 'orderform', 'open_orderform', pid]);
	}
}
