
/**
 * Javascript for new product system 2011 
 */

var SNSBasket = {
	// Ajax URL
	ajaxUrl: '/services/ajax/sns_basket.php',
	
	// Basket variables
	basket: null,
	content: null,
	price: null,
	checkout: null,

	// Titles for buttons
	titleInc: 'Tilf&oslash;j et stk. til ordren',
	titleDec: 'Fjern et stk. fra ordren',
	titleRem: 'Fjern varen helt fra ordren',
	
	/**
	 * Updates the basket with product and extras
	 * 
	 * @param productid	- Selected product's ID
	 * @param params	- Object with additional options
	 */
	updateBasket: function(productid, params) {
        var $ = jQuery;

        // If alternates exsists
		var alternate = !params.alternate ? null : params.alternate;
		// If extras exists, this is the product ID for the extras holder
		var extras = !params.extras ? null : params.extras;
        // 1 to add a product, 0 to remove a product, -1 to completely remove a product
		var add = !params.add ? 0 : params.add; 

		var lineId = 'lineId-' + productid;
        
		if (alternate) {
			lineId = 'lineId-' + $('input:radio[name=a'+productid+']:checked').val();
        }

		if (extras) {
			lineId += '-' + $('input:radio[name=e'+productid+']:checked').val();
		}

		// If extras exists
		if (extras > 0) {
			// Is the request coming from the basket or product?
			// If by product grab the top holder
			var elm = !params.elm ? $('#product' + extras) : params.elm;
			extras = new Array();
			// Success variable for extras detection
			var success = true;
			// Loop through the extras selections
			$('.extras', elm).each(function() {
				var $this = $(this);
				var val = parseInt($this.val());
				// Make sure a choice is made
				if (val >= 1) {
					extras.push(val);
				} else {
					success = false;
				}
			});
			// Abort if an extra isnt selected
			if (!success) return;
		} else {
			extras = null;
		}
		// Send request
		//$.post(this.ajaxUrl, { submitted: true, productid: productid, extras: extras, add: add }, function(data) {
		$.post(this.ajaxUrl, { action: 'add', lineId: lineId }, function(data) {
			if (data.ok) {
				// Request good update the basket
				SNSBasket.displayBasket(data.data);
			}
		}, "json");
	},

	/**
	 * Empties the basket 
	 */
	emptyBasket: function() {
		var $ = jQuery;

		// Send request
		$.post(this.ajaxUrl, { submitted: true, empty: true }, function(data) {
			if (data.ok) {
				// Request good update the basket
				SNSBasket.displayBasket(data.data);
			}
		}, "json");
	},
	
	/**
	 * Populates the basket with session data
	 * @param data	- Array with products  
	 */
	displayBasket: function(data) {
		if (this.basket == null) return;
		var $ = jQuery;

		// Clear current content
		this.content.empty();
		var totalprice = 0;

		// Loop through products data
		for (var key in data) {
			var item = data[key];
			var price = parseFloat(item.price) * parseInt(item.amount);
			var haveExtras = 0;
			totalprice += price;

			// Create product holder
			var holder = $('<div class="productHolder"></div>');

			// Create info field
			var left = $('<span class="info"></span>').html(item.name);

			// Check for extras
			if ("extras" in item) {
				haveExtras = 1;
				// Append extras info to the product
				for (var key2 in item.extras) {
					var extra = item.extras[key2];
					left.append($('<span class="extra"></span>').html(extra.name))
						.append($('<input class="extras" type="hidden" value="' + extra.id + '" />'));
				}
			}

			// Create product amount field
			var middle = $('<span class="amount"></span>').html(item.amount)
				// Add button holder
				.append($('<div></div>')

					// Add product increase button
					.append($('<span class="increase" title="' + this.titleInc + '"></span>').click(
						function() {
							var $this = $(this);
							var item = $this.data('item');
							var obj = { add: 1 };
							if (item.extras) {
								obj.extras = item.id;
								obj.elm = item.elm;
							}
							SNSBasket.updateBasket(item.id, obj);
						}).data('item', { id: item.id, extras: haveExtras, elm: left}))

					// Add product decrease button
					.append($('<span class="decrease" title="' + this.titleDec + '"></span>').click(
						function() {
							var $this = $(this);
							var item = $this.data('item');
							var obj = { add: 0 };
							if (item.extras) {
								obj.extras = item.id;
								obj.elm = item.elm;
							}
							SNSBasket.updateBasket(item.id, obj);
						}).data('item', { id: item.id, extras: haveExtras, elm: left}))
				);

			// Create product price field
			var right = $('<span class="price"></span>').html(Math.round(price));

			// Create product delete button
			var rem = $('<span class="remove"></span>')
				.append($('<span class="delete" title="' + this.titleRem + '"></span>').click(
					function() {
						var $this = $(this);
						var item = $this.data('item');
						var obj = { add: -1 };
						if (item.extras) {
							obj.extras = item.id;
							obj.elm = item.elm;
						}
						SNSBasket.updateBasket(item.id, obj);
					}).data('item', { id: item.id, extras: haveExtras, elm: left}));

			// Add fields to holder, then add that to content
			holder.append(rem, left, middle, right).appendTo(this.content);
		}

		// Assign total price
		this.price.html(totalprice);
		
		// Show or hide checkout button
		if (data.length > 0) {
			this.checkout.show();
		} else {
			this.checkout.hide();
		}
	},

	/**
	 * Initialization 
	 */
	init: function() {
		jQuery(function($) {
			// Grab basket from site
			var basket = $('div#snsBasket');

			// If basket exists
			if (basket != null) {
				var content = $('div#snsBasketBody', basket);
				var price = $('div#snsBasketFooter span.price', basket);
				var checkout = $('div#snsBasketCheckout', basket);

				SNSBasket.basket = basket;
				SNSBasket.content = content;
				SNSBasket.price = price;
				SNSBasket.checkout = checkout;

				// Send request
				$.post(SNSBasket.ajaxUrl, { submitted: true }, function(data) {
					if (data.ok) {
						// Request good update the basket
						SNSBasket.displayBasket(data.data);
					}
				}, "json");
			}
		});
	}
};

// Initialize basket
SNSBasket.init();

