﻿Asset.javascript(static + '/js/numberbox.js');
window.addEvent('domready', function() {
	LM.CartFunctions.SetUpCartHandlers();
	LM.LoginFunctions.SetUpLogin();
});

var LM = {};

LM.CartFunctions = {
	SetUpCartHandlers: function(obj) {
		if ($chk($('updateCart'))) $('updateCart').destroy();
		$$('.removeItem').each(function(item) {
			item.addEvent('click', LM.CartFunctions.RemoveItem.bindWithEvent(this, { FldKey: item.getParent().id.split('_')[1] }));
		});

		if ($chk($('items'))) {
			$('items').addEvent('submit', LM.CartFunctions.UpdateQuantity.bind(this));
			var inputs = $$('input.qty');
			//set the nubmer boxes
			inputs.each(function(item) {
				new NumberBox(item, {
					min: 1,
					max: 999,
					onComplete: LM.CartFunctions.UpdateQuantity.bind($('items'))
				});
			});
		}
	},
	AddItem: function(obj) {
		var startPriceHTML = "";
		if (obj.ItemPrice == obj.UsualPrice) {
			startPriceHTML = [new Element('br'),
			new Element('span', {
				html: "Usual price: &pound;" + obj.UsualPrice
			})]
		}
		else {
			startPriceHTML = [new Element('br'),
				new Element('span', {
					html: "Starting issue price: &pound;" + obj.ItemPrice
				}),
				new Element('br'),
				new Element('span', {
					html: "Usual price: &pound;" + obj.UsualPrice
				})]
		}
		if (obj.Issue != null) {
			var p = new Element('div', {
				'class': 'cartDiv',
				id: 'item_' + obj.FldKey,
				opacity: 0
			}).adopt(
			new Element('a', {
				'class': 'removeItem',
				href: '#',
				events: {
					'click': LM.CartFunctions.RemoveItem.bindWithEvent(this, obj)
				}
			}),
			new Element('input', {
				type: 'hidden',
				name: 'prod[' + ($$('#items p').length + 1) + '].FldKey',
				value: obj.FldKey
			}),
			new Element('input', {
				type: 'text',
				'class': 'qty',
				name: 'prod[' + ($$('#items p').length + 1) + '].Quantity',
				value: obj.Quantity
			}),
			new Element('a', {
				'class': 'items',
				href: obj.Url,
				text: obj.Title
			}),
			new Element('div', {
				'class': 'subPay'
			}).adopt(
			new Element('strong', {
				html: 'Pay nothing now'
			}),
			new Element('br'),
			new Element('span', {
				html: "Starting Issue: " + obj.Issue
			}), startPriceHTML
			)
			);
			new NumberBox(p.getElement('input.qty'), {
				min: 1,
				max: 999,
				onComplete: LM.CartFunctions.UpdateQuantity.bind($('items'))
			});
			p.inject('itemsSub');
			var play = new Fx.Slide(p, {
				onComplete: function() {
					p.tween('opacity', 0, 1);
				}
			}).hide();
		}
		else {
			var p = new Element('div', {
				'class': 'cartDiv',
				id: 'item_' + obj.FldKey,
				opacity: 0
			}).adopt(
			new Element('a', {
				'class': 'removeItem',
				href: '#',
				events: {
					'click': LM.CartFunctions.RemoveItem.bindWithEvent(this, obj)
				}
			}),
			new Element('input', {
				type: 'hidden',
				name: 'prod[' + ($$('#items p').length + 1) + '].FldKey',
				value: obj.FldKey
			}),
			new Element('input', {
				type: 'text',
				'class': 'qty',
				name: 'prod[' + ($$('#items p').length + 1) + '].Quantity',
				value: obj.Quantity
			}),
			new Element('a', {
				'class': 'items',
				href: obj.Url,
				text: obj.Title
			}),
			new Element('strong', {
				'class': 'price',
				html: '&pound;' + obj.ItemPrice
			})
			);
			new NumberBox(p.getElement('input.qty'), {
				min: 1,
				max: 999,
				onComplete: LM.CartFunctions.UpdateQuantity.bind($('items'))
			});

			p.inject('itemsOthers');
			var play = new Fx.Slide(p, {
				onComplete: function() {
					p.tween('opacity', 0, 1);
				}
			}).hide();
		}
		play.slideIn();
		this.UpdateTotal();
	},
	UpdateItem: function(obj) {
		var item = $('item_' + obj.FldKey);
		var fx = new Fx.Tween(item, {
			onComplete: function() {
				if (item.get('opacity') == 0) {
					item.getElement('input.qty').set('value', obj.Quantity);
					LM.CartFunctions.UpdateTotal();
					this.start('opacity', 0, 1);
				}
			}
		});
		fx.start('opacity', 1, 0);
	},
	UpdateTotal: function() {
		var total = 0;
		var itemCount = 0;
		$$('.cartDiv').each(function(item) {
			if ($chk(item.getElement('input.qty'))) {
				var qty = item.getElement('input.qty').get('value').toInt();
				if ($chk(item.getElement('strong.price')))
					var price = item.getElement('strong.price').get('text');
				else
					var price = '0.00'
				price = price.match(/([\d\.]+)/)[1].toFloat();
				total += qty * price;
				itemCount += qty;
			}
		});

		$('total').set('html', '&pound;' + total.toFixed(2));
		$$('.itemAmount').set('text', itemCount);
	},
	RedrawCart: function(inEuros) {
		new Request.HTML({
			url: path + '/cart/cartcontents.rails',
			update: "blah",
			onComplete: function() {
				LM.CartFunctions.SetUpCartHandlers();
			}
		}).post({
			"inEuros": inEuros
		});
	},
	RemoveItem: function(e, obj) {
		e.stop();
		new Request.JSON({
			url: path + '/cart/remove',
			onComplete: function(obj) {
				if (obj.success) {
					$('item_' + obj.FldKey).destroy();
					LM.CartFunctions.UpdateTotal();
					//update the indexes
					$$('#items p').each(function(item, index) {
						item.getElements('input').each(function(input) {
							input.name = input.name.replace(/\d+/, index);
						})
					});
				}
			}
		}).post({ id: obj.FldKey, async: true });
	},
	UpdateQuantity: function(e) {
		if ($chk(e)) e.stop();
		this.async.value = true;
		this.set('send', {
			onComplete: function(resp, text) {
				var obj = JSON.decode(resp);
				LM.CartFunctions.UpdateTotal();
			}
		});

		this.send();
	},
	UpdateLoader: function(resp, text) {
		var obj = JSON.decode(resp);
		if (obj.IsUpdate && $chk($('item_' + obj.FldKey)))
			LM.CartFunctions.UpdateItem(obj);
		else
			LM.CartFunctions.AddItem(obj);

		button.replaces(this.getElement('input + img'));
	}

}
LM.LoginFunctions = {
	SetUpLogin: function() {
		$$('#loginForm').addEvent('submit', LM.LoginFunctions.Login);
		$$('.logoutBtn').addEvent('click', LM.LoginFunctions.Logout);
		$$('.loginBG input').each(function(item) {
			item.addEvents({
				'click': function() {
					if (item.get('value') == item.defaultValue)
						item.set('value', '');
				},
				'blur': function() {
					if (item.get('value') == "")
						item.set('value', item.defaultValue);
				}
			})
		});
	},
	Login: function(e) {
		if ($chk(e)) e.stop();
		new Request.HTML({
			url: path + '/login/LoginSubmit.rails',
			update: "loginFields",
			onComplete: LM.LoginFunctions.SetUpLogin
		}).post({
			"username": $('username').value,
			"password": $('password').value
		});
	},
	Logout: function(e) {
		if ($chk(e)) e.stop();
		new Request.HTML({
			url: path + '/login/Logout.rails',
			update: "loginFields",
			onComplete: function() {
				LM.LoginFunctions.SetUpLogin();
			}
		}).post();
	}
}

function homepageVideoTracker(action, video, time) {
	//alert(action + ' ' + video + ' ' + time);
	pageTracker._trackEvent('video',action, video, time);
}

function OpenDDGuaranteeWindow() {
	window.open('/checkout/DDGuarantee','Direct Debit Guarantee','menubar=0,resizable=0,width=630,height=380');
	return false;
}

