﻿/*  Add to basket logic.
Rebuilt for new listing pages and basket 11-08-2009
*/
wffBasket = { updatingPostcode: false, formWaiting: null, callbacks: { add: [], remove: []} };

function basketPost(formData, productTitle, prefix, productId, postQuantity, item, image) {
	this.formData = formData;
	this.productTitle = productTitle;
	this.prefix = prefix;
	this.productId = productId;
	this.postQuantity = postQuantity;
	this.item = item;
	this.image = image;
	var me = this;
	this.submit = function() {
		jQuery.post('/basket/add', this.formData, function(data) {

			// Update our postcode / basket box.
			jQuery('#basketCount').text(data.intProdCount + ' item' + (data.intProdCount != 1 ? 's' : ''));
			jQuery('#basketPrice').text(data.mnyTotal);

			//get product name from data if it's set
			if (data.strLineName.length > 0) me.productTitle = data.strLineName;

			//queue up a slide-down message
			var bsktText = 'your basket has been updated.<br/><strong>' + data.intLineQty + '</strong>' + (data.intLineQty == 1 ? ' is ' : ' are ') + 'now in your basket';
			if (data.intLineQty == '0' && postQuantity != '0') {
				if (me.productTitle == undefined) {
					me.productTitle = 'Sorry, the item couldn\'t be found';
					bsktText = '';
				}
				else {
					bsktText = 'couldn\'t be added to your basket';
				}
			}
			else if (data.intLineQty == '0') {
				bsktText = 'have all been removed from your basket';
			}
			queueBasketMessage(me.productTitle, data.mnyLineTotal, bsktText, false, me.image);

			//things we always update - find all items
			this.item = me.item.add(jQuery('.' + me.prefix + '-' + me.productId));
			this.item.find('input[type=submit]').val(data.intLineQty == 0 ? 'Add to basket' : 'Add another');
			this.item.find('input[name=qty][type=hidden]').val(data.intLineQty + 1); //hidden qty fields for add-another
			this.item.find('.basketCount').text(data.intLineQty + ' in basket');
			//reset warnings
			jQuery('#warningMessage ul li:not(.minOrderAmtWarning)').remove();
			jQuery('.minOrderAmtWarning').hide();
			if (data.strError != '') {
				jQuery('#warningMessage p').html(data.strError);
				jQuery('#warningMessage').show();
				jQuery('.checkoutColumn .submitRow a.popuptrigger').removeClass('popuptrigger');
			}
			else if (jQuery('.minOrderAmtWarning').length > 0 && convertToNumber(data.mnyTotal) < convertToNumber(data.mnyMinOrderValue)) {
				jQuery('.minOrderAmtWarning').show();
				jQuery('#warningMessage:has(.minOrderAmtWarning)').show();
				jQuery('.checkoutColumn .submitRow a.popuptrigger').removeClass('popuptrigger');
			}
			else {
				jQuery('#warningMessage').hide();
				jQuery('.checkoutColumn .submitRow a.popuptrigger').addClass('popuptrigger');
			}
			//things to do if we have removed an item from our basket
			if (data.intLineQty == 0) {
				jQuery('.' + me.prefix + '-' + me.productId).removeClass('productListingInBasket');
				//execute callbacks
				for (fn in wffBasket.callbacks.remove) {
					if (typeof (wffBasket.callbacks.remove[fn]) == 'function') wffBasket.callbacks.remove[fn]();
				}
			}
			//things to do if we have added / updated items in our basket
			else {
				jQuery('.' + me.prefix + '-' + me.productId).addClass('productListingInBasket');
				//execute callbacks
				for (fn in wffBasket.callbacks.add) {
					if (typeof (wffBasket.callbacks.add[fn]) == 'function') wffBasket.callbacks.add[fn](me.formType);
				}
			}

		}, 'json');
	}
}

function basketInit(s) {
	s = s == undefined ? '.productForm' : s;
	//prevent double binding. that's bad.
	jQuery(s).unbind('submit').submit(function () {
		if (wffBasket.updatingPostcode)
			return false;
		// Make sure we have a postcode before we add products
		if (!headscapeDOM.getSubCookie("WFF", "F")) {
			wffBasket.formWaiting = jQuery(this).attr('id');
			var basket = jQuery(this).find('input[name=pid],input[name=mid],input[name=qty]').serialize();
			//use a popupbox to enter postcode
			clickFire('/franchise/change?a=addproduct', function (f) {
				f.find('form').attr('action', '/basket/add?' + basket);
			});
		}
		else {
			//find the container for the form, image, details etc. Translates as follows:
			//li for listing pages
			//div.prodDetails_intro on details pages / popup.
			//div.mealBox on meals pages (product groups)
			//tr on basket page
			//create our post object
			var p = new basketPost();
			p.item = jQuery(this).parents('li,.prodDetails_intro,.mealBox,tr').eq(0);

			var fImg = p.item.find('img:first');
			//whiz an image up to the basket box
			p.image = fImg.clone();
			//normalise the dimensions to 222x222
			if (p.image.attr('src') != undefined)
				p.image.attr('src', p.image.attr('src').replace(/&t=[0-9]+x[0-9]+$/, '&t=222x222'));
			//stick in the tools and animate
			if (fImg.length > 0) {
				p.image.appendTo('#tools')
                    .removeClass('prodImg')
                    .css({ left: (fImg.offset().left - jQuery('#tools').offset().left) - p.image.width(),
                    	top: (fImg.offset().top - jQuery('#tools').offset().top),
                    	position: 'absolute',
                    	width: '222px',
                    	height: '222px'
                    })
                    .animate({ left: 20, top: 150, opacity: 0, width: 10, height: 10 }, 800, function () { jQuery(this).remove(); });
			}
			//serialize the form before we start playing with qty valeus etc
			p.formData = jQuery(this).serialize();
			p.formType = jQuery(this).find('input#code').length == 1 ? 'code' : 'link';
			//p.productTitle = p.item.find('.productListingTitle').text();
			p.prefix = (p.item.find('input[name=pid]').length > 0) ? 'pid' : 'mid';
			p.productId = p.item.find('input[name=' + p.prefix + ']').val();
			p.postQuantity = p.item.find('input[name=qty]').val() * 1;
			if (p.postQuantity > 0) p.item.find('input[type=hidden][name=qty]').val(p.postQuantity + 1); //increment pre-emptive of multiple clicks
			//post our ajax data
			p.submit();
		}
		return false;
	});
	//submit any waiting forms
	if (wffBasket.formWaiting != null) {
		//the product is no longer in the list, apologise.
		if (jQuery('#' + wffBasket.formWaiting).length == 0) {
			queueBasketMessage('', '', 'Sorry, the product you tried to add is unavailable for this franchise.', false, null)
		}
		else {
			jQuery('#' + wffBasket.formWaiting).submit();
		}
		wffBasket.formWaiting = null;
	}

	//special stuff for actual basket page
	jQuery('.basketForm').submit(function () {
		jQuery.ajax({
			url: jQuery(this).attr('action') + '?request=partial',
			type: 'post',
			data: jQuery(this).serialize(),
			success: function (data, status) {
				//alert('complete');
				for (line in data.items) {
					if (line.quantity == 0) {
						jQuery('tr#basketLine' + data.items[line].id).fadeOut();
					}
					else {
						var row = jQuery('tr#basketLine' + data.items[line].id);
						if (jQuery.trim(row.find('.lineTotal').text()) != jQuery.trim(data.items[line].subtotal)) {
							row.find('input.quantity').val(data.items[line].quantity).end()
								 .find('.lineTotal').text(data.items[line].subtotal).flash().end();
						}
					}
				}
				//alert("data.items.length: " + data.items.length);

				//now we're up to date, let's remove zero-lines
				jQuery('.basketItems tr:has(input.quantity[value=0])').fadeOut();
				//messages and buttons
				if (data.items.length == 0) { //no items
					jQuery('#warningMessage').hide();
					jQuery('.basketItems th').hide();
					jQuery('tr.emptyBasket').show();
					jQuery('.submitRow .checkoutButton').css({ visibility: 'hidden' });
				}
				else if (data.canCheckout) { //enough items to checkout
					if (data.warning.length > 0) {
						//alert("data.items.length 1: " + data.items.length);
						jQuery('#warningMessage').show().find('p').html(data.warning);
						jQuery('#warningMessage div.title').html("You no longer qualify for this promotion");
						$("span[class='promo']").parents("tr").remove();
					}
					else {
						//alert("data.items.length 2: " + data.items.length);
						jQuery('#warningMessage').hide();
					}

					jQuery('.submitRow a.checkoutButton').show();
				}
				else { // some items, but not enough
					jQuery('#warningMessage').show().find('p').html(data.warning);
					jQuery('.submitRow a.checkoutButton').hide();
				}
				jQuery('.basketTotalPrice').text(data.total).flash();
			},
			dataType: 'json'
		});
		//jQuery.post(, , , 'json');
		return false;
	}).find('input.quantity').bind('blur', function () {
		var qty = jQuery(this).val();
		if (qty == '' || isNaN(qty)) jQuery(this).val('0');
		jQuery(this).parents('form').submit();
	}).end().find('input.remove').bind('click', function () {
		jQuery(this).parents('tr').find('input.quantity').val('0').parents('form').submit();
		return false;
	});
	jQuery('.quickAdd form').submit(function () {
		jQuery('#code').val('').focus();
		//alert("product code: " + jQuery('#code').val());
	});
	jQuery('.addAllToBasket').click(function () {
		jQuery('.productList .productForm, #recommendations .productForm').submit();
	});
}

// queue a new basket message
//temp messages (such as please wait) will stay on screen til a new action is queued. They will only show if there is currently nothing else occurring (zero queue)
function queueBasketMessage(product, price, text, temp, img) {
	if (product == undefined) product = '';
	if (jQuery('#toolsOuterContainer').css('position') == 'static') return false;
	if (temp && jQuery('#basketLatest').queue().length > 0) return; // ignore temp messages if we have a current one displaying
	jQuery('#tools').addClass('active');
	jQuery('#toolsContainer').animate({ backgroundColor: '#fff469' }, 500)
                             .animate({ backgroundColor: '#fff469' }, 1000)
                             .animate({ backgroundColor: '#eeeeee' }, 500);
	jQuery('#toolsAdded').queue(function() { jQuery(this).find('.mealName').text(product); $(this).dequeue(); })
                         .queue(function() { jQuery(this).find('.mealPrice').text((+price > 0) ? ' (£' + price + ')' : ''); $(this).dequeue(); })
                         .queue(function() { jQuery(this).find('.addedConfirm').html(text); $(this).dequeue(); })
                         .queue(function() { jQuery(this).find('dt').html(img != null ? img.clone().css({ position: 'static', left: 0, top: 0, opacity: 1, width: 70, height: 70 }).addClass('toolsAddedImg') : ''); $(this).dequeue(); })
                         .slideDown(250)
                         .animate({ opacity: '1' }, 1000)
						 .slideUp(250, function() { jQuery('#tools').removeClass('active'); });
}

jQuery.fn.extend({
	flash: function() {
		return this.each(function() {
			jQuery(this).css({ backgroundColor: '#F4E400' }).animate({ backgroundColor: '#ffffff' }, 1000);
		});
	}
});
