/* SHOPPING BASKET FUNCTIONS */

var warning_text = ' ';
var specialPricesLoaded = false;

function removeItem(ID) {
	f = g('basket_form');
	f.object.value = ID;
	f.action.value = 'delete';
	f.submit();
}

function editItem(ID) {
	f = g('basket_form');
	f.object.value = ID;
	f.action.value = 'edit';
	// alert(warning_text);
	f.submit();
}

function requestSpecialPrice() {

	if (specialPricesLoaded)
		return;

	var user = prompt(username_prompt);
	if (user != '' && user != null) {
		var pass = prompt(password_prompt);
		if (pass != '' && pass != null) {
			itemStr = '';
			for ( var i = 0; i < items.length; i++) {
				itemStr += (itemStr == '' ? '' : '&') + 'items[]=' + items[i];
			}
			var req = new AjaxRequest('typo3conf/ext/iwshop/extra/AJAX.php?getSpecialPrices:' + user + ':' + MD5(salt + MD5(pass) + salt) + ':' + salt,
					'POST', itemStr, loadSpecialPrices);
			req.send();
		}
	}
}

function loadSpecialPrices(XML) {

	if (getXMLvalue(XML, 'status') != 'OK') {
		alert('Error: ' + getXMLvalue(XML, 'msg'));
		return;
	}

	var deals = XML.getElementsByTagName('numeric');
	for ( var i = 0; i < deals.length; i++) {
		var deal = deals[i];

		var id = getXMLvalue(deal, 'itemID');
		var oldPrice = getXMLvalue(deal, 'oldPrice');
		var newPrice = getXMLvalue(deal, 'newPrice');
		if (newPrice != oldPrice) {
			g('price-span-discounted-' + id).innerHTML = newPrice + ' ' + currency_title;
		} else {
			g('price-span-discounted-' + id).innerHTML = '';
		}

	}

	g('total-discount-price').innerHTML = getXMLvalue(XML, 'total') + ' ' + currency_title;
	// specialPricesLoaded = true;
}

function PriceTag(elem) {
	var el = elem;

	this.price = function(val) {
		if (typeof val == "undefined") {
			return this.getPrice();
		} else {
			this.setPrice(val);
		}
	};

	var hasValue = function() {
		return el[0].nodeName.match(/input|select|textarea/i);
	};

	this.getPrice = function() {
		return parseInt(hasValue() ? el.val() : el.text());
	};

	this.setPrice = function(value) {
		return hasValue() ? el.val(value) : el.text(value);
	};

	return this;
}

function getBasketState() {
	var res = {
		code: $('.gift-discount input').val()
	};
	
	var items = $('tr.product');
	
	var jsonItems = [];
	
	$.each(items, function(ix, prod) {
		var qinp = $(prod).find('.quantity input');
		var ID = qinp.attr('id').replace(/\D/g, '');
		
		jsonItems.push({
			'ID' : ID,
			'quantity' : parseInt(qinp.val())
		});
	});
	
	res.items = $.toJSON(jsonItems);
	
	return res;
}

function setBasketState(resp) {
	var newShipPrice = parseFloat(resp.freight_price);
	var newGDPrice = parseFloat(resp.gift_discount_price);
	var newItemsPrice = parseFloat(resp.image_price);
	var newTotalPrice = newShipPrice + newItemsPrice + newGDPrice;
	
	var shipPricer = new PriceTag($('.shipping_options #shipping_price'));
	var giftDiscountPricer = new PriceTag($('.gift_discount .price'));
	var totalPricer = new PriceTag($('.total .price span:first'));

	$.each(resp.items, function(ix, priceInfo) {
		var ID = ix;
		var ImgDiscount = parseFloat(priceInfo.discount);
		var newImgPrice = parseFloat(priceInfo.result);

		var rowPricer = new PriceTag($('#price-span-' + ID));
		rowPricer.price(newImgPrice.toFixed(2) + '\xA0' + currency_title);

		var discPricer = new PriceTag($('#discount-span-' + ID));
		if(ImgDiscount > 0) {
			discPricer.price(ImgDiscount + '\xA0%');
		} else {
			discPricer.price('');
		}
	});	
	
	giftDiscountPricer.price(newGDPrice.toFixed(2) + '\xA0' + currency_title);
	shipPricer.price(newShipPrice.toFixed(2) + '\xA0' + currency_title);
	totalPricer.price(newTotalPrice.toFixed(2) + '\xA0' + currency_title);
}

function updateQuantity() {
	var $this = $(this);
	var newVal = parseInt($this.val());
	var lastVal = parseInt($this.data('currentQuantity'));
	if (newVal == lastVal) {
		$this.val(newVal); // just in case they entered 3.6 this will reset to 3
	} else if (newVal < 1 || isNaN(newVal)) {
		$this.val(lastVal); // revert quantity edit
		tb_show(error_label, '?#TB_inline=1&width=200&height=100&inlineId=message-quantity');
	} else {
		overlayShow($('#content'));
		var quantifier = $this;
		var quantity = quantifier.val();
		var ID = $this.attr('id').replace(/\D/g, '');
		var shipPricer = new PriceTag($('.shipment .price'));
		var giftDiscountPricer = new PriceTag($('.gift_discount .price'));
		var totalPricer = new PriceTag($('.total .price span:first'));
		
		var postdata = getBasketState();
		postdata.cmd = 'updateBasket';
		
		$.post('index.php?eID=iwshop', postdata, function(resp) {
			if (!resp || resp.status != 'OK') {
				alert('Error: ' + (resp) ? resp.msg : 'Unknown error');
				$this.val($this.data('currentQuantity')); // revert quantity edit
			} else {
				$this.data('currentQuantity', quantity);

				setBasketState(resp);
			}
			overlayHide();
		}, 'json');
	}
}

function PriceRow(elem) {
	var $elem = $(elem);
	var origVal = parseInt($elem.val());
	$elem.data('originalQuantity', origVal);
	$elem.data('currentQuantity', origVal);

	$elem.bind('blur', updateQuantity).bind('keypress', function() {
		var $this = this;
		window.setTimeout(function() {
			updateQuantity.call($this);
		}, 100);
	});

	$elem.keyup(function(e) {
		if (e.keyCode == 13) {
			$elem.trigger('blur');
		}
	});
}

function updateGiftDiscount(e) {
	var $this = $('.gift-discount input');
	var code = $this.val();

	var lastCode = $this.data('currentCode');
	if(lastCode == code) {
		return;
	}
	
	overlayShow($('#content'));

	var postdata = getBasketState();
	postdata.cmd = 'updateBasket';
	
	$.post('index.php?eID=iwshop', postdata, function(resp) {
		if (!resp) {
			tb_show(error_label, '?#TB_inline=1&width=250&height=150&inlineId=message-giftcard-code');
			$this.val('');
			$this.data('currentCode', '');
		} else {
			if(resp.status != 'OK') {
				tb_show(error_label, '?#TB_inline=1&width=250&height=150&inlineId=message-giftcard-code');
				$this.val('');
				$this.data('currentCode', '');
			}
			$this.data('currentCode', code);
			
			setBasketState(resp);
		}
		overlayHide();
	}, 'json');
	return false;
};

$(function() {
	var editables = $('.quantity input[type="text"]');

	$.each(editables, function(ix, el) {
		new PriceRow(el);
	});

	var GD = $('.gift-discount');
	var GDcode = GD.find('input');
	GDcode.data('originalCode', GDcode.val());
	GDcode.data('currentCode', GDcode.val());
//	GDcode.bind('blur', updateGiftDiscount);
	GDcode.keyup(function(e) {
		if (e.keyCode == 13) {
			updateGiftDiscount(e);
		}
	});
	GD.find('a').click(updateGiftDiscount);
});

